use of org.bimserver.models.store.Project in project BIMserver by opensourceBIM.
the class GetAllProjectsDatabaseAction method execute.
@Override
public Set<Project> execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
User user = getUserByUoid(authorization.getUoid());
Not notStoreProject = new Not(new AttributeCondition(StorePackage.eINSTANCE.getProject_Name(), new StringLiteral(Database.STORE_PROJECT_NAME)));
HasReferenceToCondition authorized = new HasReferenceToCondition(StorePackage.eINSTANCE.getProject_HasAuthorizedUsers(), user);
Condition condition = new IsOfTypeCondition(StorePackage.eINSTANCE.getProject()).and(notStoreProject);
// }
if (onlyActive) {
condition = new AndCondition(condition, new AttributeCondition(StorePackage.eINSTANCE.getProject_State(), new EnumLiteral(ObjectState.ACTIVE)));
}
if (user.getUserType() != UserType.ADMIN && user.getUserType() != UserType.SYSTEM) {
condition = condition.and(authorized);
condition = condition.and(new AttributeCondition(StorePackage.eINSTANCE.getProject_State(), new EnumLiteral(ObjectState.ACTIVE)));
}
Map<Long, Project> results = getDatabaseSession().query(condition, Project.class, OldQuery.getDefault());
Set<Project> resultSet = new HashSet<Project>();
for (Project p : results.values()) {
if (p.getParent() == null || !onlyTopLevel) {
resultSet.add(p);
}
}
for (Project project : results.values()) {
addParentProjects(resultSet, project);
}
return resultSet;
}
use of org.bimserver.models.store.Project in project BIMserver by opensourceBIM.
the class GetAllRelatedProjectsDatabaseAction method addProjects.
private void addProjects(List<SProjectSmall> list, Project project, User user) {
if (project.getState() == ObjectState.DELETED && !(authorization instanceof AdminAuthorization)) {
return;
}
list.add(GetAllProjectsSmallDatabaseAction.createSmallProject(authorization, bimServer, project, user));
List<Project> subProjects = new ArrayList<Project>(project.getSubProjects());
Collections.sort(subProjects, new Comparator<Project>() {
@Override
public int compare(Project o1, Project o2) {
return o1.getName().compareTo(o2.getName());
}
});
for (Project subProject : subProjects) {
addProjects(list, subProject, user);
}
}
use of org.bimserver.models.store.Project in project BIMserver by opensourceBIM.
the class GetAllRelatedProjectsDatabaseAction method execute.
@Override
public List<SProjectSmall> execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
List<SProjectSmall> list = new ArrayList<SProjectSmall>();
Project project = getDatabaseSession().get(StorePackage.eINSTANCE.getProject(), poid, OldQuery.getDefault());
Project rootProject = getRootProject(project);
User user = getUserByUoid(authorization.getUoid());
addProjects(list, rootProject, user);
return list;
}
use of org.bimserver.models.store.Project in project BIMserver by opensourceBIM.
the class ServiceImpl method checkinFromUrl.
@Override
public Long checkinFromUrl(Long poid, String comment, Long deserializerOid, String fileName, String urlString, Boolean merge, Boolean sync) throws ServerException, UserException {
requireAuthenticationAndRunningServer();
final DatabaseSession session = getBimServer().getDatabase().createSession();
String username = "Unknown";
String userUsername = "Unknown";
try {
if (getBimServer().getCheckinsInProgress().containsKey(poid)) {
throw new UserException("Checkin in progress on this project, please try again later");
}
User user = (User) session.get(StorePackage.eINSTANCE.getUser(), getAuthorization().getUoid(), OldQuery.getDefault());
username = user.getName();
userUsername = user.getUsername();
Path homeDirIncoming = getBimServer().getHomeDir().resolve("incoming");
if (!Files.isDirectory(homeDirIncoming)) {
Files.createDirectory(homeDirIncoming);
}
Path userDirIncoming = homeDirIncoming.resolve(userUsername);
if (!Files.exists(userDirIncoming)) {
Files.createDirectory(userDirIncoming);
}
Project project = session.get(poid, OldQuery.getDefault());
if (project == null) {
throw new UserException("No project found with poid " + poid);
}
Long topicId = initiateCheckin(poid, deserializerOid);
URL url = new URL(urlString);
URLConnection openConnection = url.openConnection();
InputStream input = openConnection.getInputStream();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
if (fileName == null) {
if (urlString.contains("/")) {
fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
} else {
fileName = urlString;
}
if (fileName.contains("?")) {
fileName = fileName.substring(0, fileName.indexOf("?"));
}
fileName = URLDecoder.decode(fileName, Charsets.UTF_8.name());
} else {
fileName = dateFormat.format(new Date()) + "-" + fileName;
}
Path file = userDirIncoming.resolve(fileName);
if (fileName.contains(" ")) {
fileName = fileName.replace(" ", "_");
}
return checkinInternal(topicId, poid, comment, deserializerOid, (long) openConnection.getContentLength(), fileName, input, merge, sync, session, username, userUsername, project, file, -1);
// DeserializerPluginConfiguration deserializerPluginConfiguration = session.get(StorePackage.eINSTANCE.getDeserializerPluginConfiguration(), deserializerOid, OldQuery.getDefault());
// if (deserializerPluginConfiguration == null) {
// throw new UserException("Deserializer with oid " + deserializerOid + " not found");
// }
// OutputStream outputStream = Files.newOutputStream(file);
// InputStream inputStream = new MultiplexingInputStream(input, outputStream);
// DeserializerPlugin deserializerPlugin = (DeserializerPlugin) getBimServer().getPluginManager().getPlugin(deserializerPluginConfiguration.getPluginDescriptor().getPluginClassName(), true);
// ObjectType settings = deserializerPluginConfiguration.getSettings();
//
// Deserializer deserializer = deserializerPlugin.createDeserializer(new PluginConfiguration(settings));
// deserializer.init(getBimServer().getDatabase().getMetaDataManager().getPackageMetaData("ifc2x3tc1"));
//
// IfcModelInterface model = deserializer.read(inputStream, fileName, 0, null);
//
// CheckinDatabaseAction checkinDatabaseAction = new CheckinDatabaseAction(getBimServer(), null, getInternalAccessMethod(), poid, getAuthorization(), model, comment, fileName, merge);
// LongCheckinAction longAction = new LongCheckinAction(-1L, getBimServer(), username, userUsername, getAuthorization(), checkinDatabaseAction);
// getBimServer().getLongActionManager().start(longAction);
// if (sync) {
// longAction.waitForCompletion();
// }
// return longAction.getProgressTopic().getKey().getId();
} catch (UserException e) {
throw e;
} catch (Throwable e) {
LOGGER.error("", e);
throw new ServerException(e);
} finally {
session.close();
}
}
use of org.bimserver.models.store.Project in project BIMserver by opensourceBIM.
the class ServiceImpl method triggerRevisionService.
@Override
public void triggerRevisionService(Long roid, Long soid) throws ServerException, UserException {
DatabaseSession session = getBimServer().getDatabase().createSession(OperationType.READ_ONLY);
try {
Revision revision = (Revision) session.get(StorePackage.eINSTANCE.getRevision(), roid, OldQuery.getDefault());
if (revision == null) {
throw new UserException("No revision found for roid " + roid);
}
NewService newService = session.get(StorePackage.eINSTANCE.getNewService(), soid, OldQuery.getDefault());
if (revision.getServicesLinked().contains(newService)) {
// We don't want no loops
return;
}
String url = newService.getResourceUrl();
SerializerPluginConfiguration serializer = newService.getSerializer();
PackageMetaData pmd = getBimServer().getMetaDataManager().getPackageMetaData(revision.getProject().getSchema());
Query query = DefaultQueries.all(pmd);
Long topicId = download(Collections.singleton(roid), new JsonQueryObjectModelConverter(pmd).toJson(query).toString(), serializer.getOid(), false);
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
LongAction<?> longAction = getBimServer().getLongActionManager().getLongAction(topicId);
if (longAction == null) {
throw new UserException("No data found for topicId " + topicId);
}
SCheckoutResult result;
if (longAction instanceof LongStreamingDownloadAction) {
LongStreamingDownloadAction longStreamingDownloadAction = (LongStreamingDownloadAction) longAction;
if (longStreamingDownloadAction.getErrors().isEmpty()) {
try {
result = longStreamingDownloadAction.getCheckoutResult();
} catch (SerializerException e) {
throw new UserException(e);
}
} else {
LOGGER.error(longStreamingDownloadAction.getErrors().get(0));
throw new ServerException(longStreamingDownloadAction.getErrors().get(0));
}
} else {
LongDownloadOrCheckoutAction longDownloadAction = (LongDownloadOrCheckoutAction) longAction;
try {
longDownloadAction.waitForCompletion();
if (longDownloadAction.getErrors().isEmpty()) {
result = longDownloadAction.getCheckoutResult();
} else {
LOGGER.error(longDownloadAction.getErrors().get(0));
throw new ServerException(longDownloadAction.getErrors().get(0));
}
} catch (Exception e) {
LOGGER.error("", e);
throw new ServerException(e);
}
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LOGGER.info("Starting serialization");
DataSource datasource = result.getFile().getDataSource();
if (datasource instanceof ExtendedDataSource) {
((ExtendedDataSource) datasource).writeToOutputStream(baos, null);
}
LOGGER.info("Serialization done");
if (newService.getAccessToken() != null) {
httpPost.setHeader("Authorization", "Bearer " + newService.getAccessToken());
}
httpPost.setHeader("Input-Type", newService.getInput());
httpPost.setHeader("Output-Type", newService.getOutput());
httpPost.setEntity(new ByteArrayEntity(baos.toByteArray()));
long start = System.nanoTime();
CloseableHttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 401) {
throw new UserException("Remote service responded with a 401 Unauthorized");
} else if (response.getStatusLine().getStatusCode() == 200) {
Header[] headers = response.getHeaders("Content-Disposition");
String filename = "unknown";
if (headers.length > 0) {
String contentDisposition = headers[0].getValue();
if (contentDisposition.contains("filename=")) {
int indexOf = contentDisposition.indexOf("filename=") + 10;
filename = contentDisposition.substring(indexOf, contentDisposition.indexOf("\"", indexOf + 1));
} else {
filename = contentDisposition;
}
}
Header dataTitleHeader = response.getFirstHeader("Data-Title");
String dataTitle = newService.getName() + " Results";
if (dataTitleHeader != null) {
dataTitle = dataTitleHeader.getValue();
}
byte[] responseBytes = ByteStreams.toByteArray(response.getEntity().getContent());
long end = System.nanoTime();
Action action = newService.getAction();
if (action instanceof StoreExtendedData) {
SFile file = new SFile();
file.setData(responseBytes);
file.setFilename(filename);
file.setSize(responseBytes.length);
file.setMime(response.getHeaders("Content-Type")[0].getValue());
Long fileId = uploadFile(file);
SExtendedData extendedData = new SExtendedData();
extendedData.setAdded(new Date());
extendedData.setRevisionId(roid);
extendedData.setTitle(dataTitle);
extendedData.setSize(responseBytes.length);
extendedData.setFileId(fileId);
extendedData.setSchemaId(getExtendedDataSchemaByName(newService.getOutput()).getOid());
extendedData.setTimeToGenerate((end - start) / 1000000);
addExtendedDataToRevision(roid, extendedData);
} else if (action instanceof CheckinRevision) {
CheckinRevision checkinRevision = (CheckinRevision) action;
Project targetProject = checkinRevision.getProject();
String extension = filename.substring(filename.lastIndexOf(".") + 1);
SDeserializerPluginConfiguration deserializer = getSuggestedDeserializerForExtension(extension, targetProject.getOid());
Long checkingTopicId = initiateCheckin(targetProject.getOid(), deserializer.getOid());
checkinInitiatedInternal(checkingTopicId, targetProject.getOid(), dataTitle, deserializer.getOid(), (long) responseBytes.length, filename, new DataHandler(new ByteArrayDataSource(responseBytes, "ifc")), false, true, newService.getOid());
}
} else {
throw new UserException("Remote service responded with a " + response.getStatusLine());
}
} catch (Exception e) {
handleException(e);
} finally {
session.close();
}
}
Aggregations