Skip to content

Commit

Permalink
Merge pull request #628 from SynBioHub/checkbackend
Browse files Browse the repository at this point in the history
Checkbackend
  • Loading branch information
danielfang97 authored Apr 28, 2024
2 parents 5c3b7de + 528dd32 commit 423e08e
Show file tree
Hide file tree
Showing 15 changed files with 112 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,14 @@ public String deletePlugin(@RequestParam Map<String,String> allParams, HttpServl
@GetMapping(value = "/admin/registries")
@ResponseBody
public JsonNode getRegistries() throws IOException {
return ConfigUtil.get("webOfRegistries");

try {
JsonNode result = ConfigUtil.get("webOfRegistries");
return result;
} catch (IOException e) {
e.printStackTrace();
// Optionally, handle the exception or log more details here.
throw e; // rethrow the exception if you want to maintain the current method signature
}
}

@PostMapping(value = "/admin/saveRegistry")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.synbiohub.sbh3.controllers;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.synbiohub.sbh3.services.DownloadService;
import com.synbiohub.sbh3.utils.ConfigUtil;
Expand All @@ -13,7 +12,6 @@
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayInputStream;
Expand All @@ -30,9 +28,16 @@ public class DownloadController extends AntPathMatcher {
private final ObjectMapper mapper;

@GetMapping(value = "/public/{db}/{id}/{ver}/sbol") // Separate mapping for private components /user/{username}/{db}/{id}/{ver}
public ResponseEntity<?> getSBOLRecursiveRDFDownload(@PathVariable String db, @PathVariable String id, @PathVariable String ver) throws IOException {
return getInputStreamResourceResponseEntity(db, id, ver);
}

@GetMapping(value = "/public/{db}/{id}/{ver}") // Separate mapping for private components /user/{username}/{db}/{id}/{ver}
public ResponseEntity<?> getSBOLRecursiveRDF(@PathVariable String db, @PathVariable String id, @PathVariable String ver) throws IOException {
// var uri = request.getRequestURL().toString();
// String splitUri = uri.split("/sbol")[0]; //TODO replace http://localhost:6789 with https://synbiohub.org
return getInputStreamResourceResponseEntity(db, id, ver);
}

private ResponseEntity<InputStreamResource> getInputStreamResourceResponseEntity(String db, String id, String ver) throws IOException {
String splitUri = ConfigUtil.get("defaultGraph").toString().replace("\"","") + "/" + db + "/" + id + "/" + ver;
String uri = splitUri + "/sbol";

Expand All @@ -50,7 +55,7 @@ public ResponseEntity<?> getSBOLRecursiveRDF(@PathVariable String db, @PathVaria
//.contentLength(results.length)
.contentType(
MediaType.parseMediaType("application/xml"))
.header("Content-Disposition", "attachment; filename=\"" + uriArr[uriArr.length-3] + ".xml\"")
.header("Content-Disposition", "attachment; filename=\"" + uriArr[uriArr.length - 3] + ".xml\"")
.body(new InputStreamResource(new ByteArrayInputStream(byteOutput.toByteArray())));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@
import org.json.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.json.Json;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

@RestController
Expand Down Expand Up @@ -199,8 +197,9 @@ public String getTypeCount(@PathVariable("type") String type, HttpServletRequest
*/
@RequestMapping(value = "/sparql", headers = "Accept=application/json")
@ResponseBody
public String getSPARQL(@RequestParam String query) throws IOException {
return searchService.SPARQLQuery(query);
public String getSPARQL(@RequestParam Map<String, String> params) throws IOException {
System.out.println(params);
return searchService.SPARQLQuery(params.get("query"));
}

// @GetMapping(value = "/search/**")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.cors()
.and()
.authorizeHttpRequests()
.requestMatchers("/setup", "/login", "/register", "/search", "/search/**", "/searchCount", "/searchCount/**", "/twins", "/uses", "/similar", "/sbol", "/sbolnr", "/metadata", "/gb", "/fasta", "/gff", "/download", "/public/**", "/sparql", "/ComponentDefinition/**", "/**/count", "/count", "/admin/theme").permitAll()
.requestMatchers("/setup", "/login", "/register", "/search", "/search/**", "/searchCount", "/searchCount/**", "/twins", "/uses", "/similar", "/sbol", "/sbolnr", "/metadata", "/gb", "/fasta", "/gff", "/download", "/public/**", "/sparql", "/ComponentDefinition/**", "/**/count", "/count", "/admin/theme", "/admin/registries", "admin/plugins").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -350,7 +350,7 @@ public String SPARQLQuery(String query) throws IOException {
HashMap<String, String> params = new HashMap<>();
params.put("default-graph-uri", ConfigUtil.get("defaultGraph").asText());
params.put("query", query);

System.out.println(query.getClass().getName());
url = ConfigUtil.get("sparqlEndpoint").asText() + "?default-graph-uri={default-graph-uri}&query={query}&format=json&";
// url = ConfigUtil.get("sparqlEndpoint").asText() + "?default-graph-uri={default-graph-uri}&query={query}";
// has to be the first one. without format json, getting root collections fails
Expand All @@ -369,7 +369,7 @@ public byte[] SPARQLRDFXMLQuery(String query) throws IOException {
httpHeaders.add("Accept", "application/rdf+xml");
HttpEntity entity = new HttpEntity(httpHeaders);

url = ConfigUtil.get("sparqlEndpoint").asText() + "?default-graph-uri={default-graph-uri}&query={query}";
url = ConfigUtil.get("sparqlEndpoint").asText();

var rest = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class, params);
return rest.getBody();
Expand All @@ -385,12 +385,12 @@ public byte[] queryOldSBHSparqlEndpoint(String WOREndpoint, String query) throws
String url;
HashMap<String, String> params = new HashMap<>();
// params.put("default-graph-uri", ConfigUtil.get("defaultGraph").asText());
params.put("query", query);
params.put("format", "application/rdf+xml");
// params.put("query", query);
// params.put("format", "application/rdf+xml");
HttpHeaders httpHeaders = new HttpHeaders();
// httpHeaders.add("Accept", "application/json");
httpHeaders.add("Accept", "application/rdf+xml");
HttpEntity entity = new HttpEntity<>("body", httpHeaders);
httpHeaders.add("Accept", "text/plain");
HttpEntity entity = new HttpEntity<>(httpHeaders);

// url = WOREndpoint + "/sparql?query="+query;
// var result = restTemplate.getForObject(url, String.class);
Expand Down
4 changes: 2 additions & 2 deletions frontend/.env.development
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
backend="http://localhost:6789"
backendSS="http://localhost:6789"
backend="http://localhost:7777"
backendSS="http://localhost:7777"
29 changes: 19 additions & 10 deletions frontend/components/Admin/Registries.js
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ const sortMethods = {

const useRegistries = (token, dispatch) => {
const { data, error } = useSWR(
[`${publicRuntimeConfig.backend}/admin/registries`, token, dispatch],
[`${publicRuntimeConfig.backend}/admin/registries`, dispatch],
fetcher
);
return {
Expand All @@ -334,13 +334,12 @@ const useRegistries = (token, dispatch) => {
};
};

const fetcher = (url, token, dispatch) =>
const fetcher = (url, dispatch) =>
axios
.get(url, {
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
'X-authorization': token
Accept: 'application/json'
}
})
.then(response => response.data)
Expand All @@ -352,14 +351,24 @@ const fetcher = (url, token, dispatch) =>

export async function processUrl(inputUrl, token, dispatch) {

const data = await fetcher(`${publicRuntimeConfig.backend}/admin/registries`, token, dispatch);
const data = await fetcher(`${publicRuntimeConfig.backend}/admin/registries`, dispatch);

if (data) {
const registries = data.registries;


if (data && data.registries) {
let registries;
// Check if data.registries is an array
if (data.registries && Array.isArray(data.registries)) {
registries = data.registries;
} else if (data && typeof data === 'object') {
registries = [data]; // This is an example, adjust based on your needs
} else {
registries = [];
}

for (const registry of registries) {
if (inputUrl.startsWith(registry.uri)) {
const urlRemovedForLink = inputUrl.replace(registry.uri, "");
const urlRemovedForLink = inputUrl.replace(registry.uri, ""); // TODO: Should only strip for only "you"
const urlReplacedForBackend = inputUrl.replace(registry.uri, registry.url);
return { urlRemovedForLink, urlReplacedForBackend };
}
Expand All @@ -371,9 +380,9 @@ export async function processUrl(inputUrl, token, dispatch) {

export async function processUrlReverse(inputUrl, token, dispatch) {

const data = await fetcher(`${publicRuntimeConfig.backend}/admin/registries`, token, dispatch);
const data = await fetcher(`${publicRuntimeConfig.backend}/admin/registries`, dispatch);

if (data) {
if (data && data.registries) {
const registries = data.registries;

for (const registry of registries) {
Expand Down
4 changes: 3 additions & 1 deletion frontend/components/Viewing/Collection/Members.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTrash, faUnlink } from '@fortawesome/free-solid-svg-icons';
import { getAfterThirdSlash } from '../ViewHeader';
import Status, { useStatus } from '../../Admin/Status';
import { useTheme } from '../../Admin/Theme';

/* eslint sonarjs/cognitive-complexity: "off" */

Expand All @@ -51,6 +52,7 @@ export default function Members(properties) {
const [typeFilter, setTypeFilter] = useState('Show Only Root Objects');
const dispatch = useDispatch();
const [processedUri, setProcessedUri] = useState(publicRuntimeConfig.backend);
const { theme } = useTheme();

let preparedSearch =
search !== ''
Expand All @@ -74,7 +76,7 @@ export default function Members(properties) {

const parameters = {
from: '',
graphPrefix: 'https://synbiohub.org/', // TODO: Maybe get this from somewhere?
graphPrefix: `${theme.uriPrefix}`, // TODO: Maybe get this from somewhere?
collection: properties.uri,
sort: sort,
search: preparedSearch,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,17 @@ export default function executeQueryFromTableJSON(
) {
if (typeof uri === "undefined") {
uri = "URI is undefined";
}
}

console.log(uri);


return getQueryResponse(
dispatch,
prefixes + '\n' + buildQuery(uri, table),
{},
{ uri },
'',
false,
urlOverride
urlOverride,
uri
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,12 @@ function TableRenderer({ uri, prefixes, table, metadata, owner }) {
const token = useSelector(state => state.user.token);
const [content, setContent] = useState(null);
const dispatch = useDispatch();
console.log(uri);
console.log(prefixes);
console.log(table);
useEffect(() => {
executeQueryFromTableJSON(dispatch, uri, prefixes, table).then(response => {
console.log(response);
setContent(parseQueryResult(table, response, prefixes));
});
}, [uri, prefixes, table]);
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/Viewing/Sections/Details/Details.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default function Details(properties) {
if (details == undefined) {
getQueryResponse(dispatch, getDetails, { uri: properties.uri }).then(
details => {
if (details.length > 0) setDetails(details[0]);
if (details && details.length > 0) setDetails(details[0]);
}
);

Expand Down
12 changes: 10 additions & 2 deletions frontend/pages/[...view].js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import getQueryResponse from '../sparql/tools/getQueryResponse';
import { addError } from '../redux/actions';
import styles from '../styles/view.module.css';
import LinkedSearch from '../components/Search/StandardSearch/LinkedSearch';
import { useTheme } from '../components/Admin/Theme';

export default function View({ data, error }) {
const dispatch = useDispatch();
Expand All @@ -24,7 +25,7 @@ export default function View({ data, error }) {
const token = useSelector(state => state.user.token);
const url = view ? view.join('/') : '';
const [metadata, setMetadata] = useState();
const uri = `https://synbiohub.org/${url}`;
const { theme } = useTheme();
const [urlExists, setUrlExists] = useState(true); // New state for URL existence
const backenduri = `${publicRuntimeConfig.backend}/${url}`;

Expand Down Expand Up @@ -65,13 +66,20 @@ export default function View({ data, error }) {
marginTop: '-10vh',
};

let uri;
// let uri = `https://dan.org/${url}`;
if (theme) {
uri = `${theme.uriPrefix}${url}`;
}


useEffect(() => {
// Check if URL exists
axios.get(backenduri)
.then(response => {
// URL exists
setUrlExists(true);
if (!metadata)
if (!metadata && uri)
getQueryResponse(dispatch, getMetadata, { uri: uri }, token).then(
metadata => setMetadata(metadata)
);
Expand Down
2 changes: 1 addition & 1 deletion frontend/public/commitHash.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
9dae7d40f1fe6b8ebf1ba96d0e4b585927c0a95b
f6f9da07901a90dad77c15690464facfc1fa8e67
20 changes: 19 additions & 1 deletion frontend/sparql/tools/getQueryResponse.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ export default async function getQueryResponse(
admin,
urlOverride
) {
console.log(options);

query = loadTemplate(query, options);

const currentURL = window.location.href;
Expand All @@ -23,7 +25,9 @@ export default async function getQueryResponse(
const result = regex.exec(currentURL)[0];
const lastSlash = result.lastIndexOf('/');
const graphURL = result.substring(0, lastSlash);
graphEx = `&default-graph-uri=https://synbiohub.org${graphURL}`;
const uriPrefix = getUrlBeforeThirdSlash(options.uri);
console.log(`${uriPrefix}${graphURL}`);
graphEx = `&default-graph-uri=${uriPrefix}${graphURL}`;
}

const params = admin ? '/admin/sparql?query=' : '/sparql?query=';
Expand All @@ -32,6 +36,9 @@ export default async function getQueryResponse(
urlOverride || publicRuntimeConfig.backend
}${params}${encodeURIComponent(query)}${graph}`;

console.log(options);
console.log(url);

const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
Expand Down Expand Up @@ -66,3 +73,14 @@ const processResults = results => {
return resultObject;
});
};

function getUrlBeforeThirdSlash(url) {
if (typeof url !== 'string') return '';
let slashCount = 0, result = '';
for (let i = 0; i < url.length; i++) {
if (url[i] === '/') slashCount++;
if (slashCount === 3) break;
result += url[i];
}
return result;
}
Loading

0 comments on commit 423e08e

Please sign in to comment.