update asset source #82

null pointer when using non existing workspace or project in updateAsset Source #81
This commit is contained in:
Nicolas Héron 2020-09-09 19:02:17 +02:00
commit e3375f4216
5 changed files with 491 additions and 244 deletions

View file

@ -36,7 +36,14 @@ public class DababaseContentInit {
User adminUser = userRepository.findByLogin("admin");
if (adminUser==null){
/**
* admin The administrator
* analyst The analyst
* developer The developer
* manager The manager
* user The end user
* kiemgmt KIE management user
*/
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"process-admin"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"manager"));
userRolesRepository.save( new UserRoles(UUID.randomUUID().toString(),"admin"));

View file

@ -25,6 +25,7 @@ import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.types.ObjectId;
import org.jboss.errai.security.shared.api.Group;
import org.jboss.errai.security.shared.api.GroupImpl;
import org.jboss.errai.security.shared.api.Role;
@ -102,11 +103,11 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
User user = fillUser(userName, document);
users.add(user);
});
boolean hasNextPage=true;
if ((request.getPageSize() * (request.getPage())>totalNumber)){
hasNextPage=false;
boolean hasNextPage = true;
if ((request.getPageSize() * (request.getPage()) > totalNumber)) {
hasNextPage = false;
}
SearchResponse<User> response = new SearchResponseImpl(users, request.getPage(),request.getPageSize(),Long.valueOf(totalNumber).intValue(), hasNextPage);
SearchResponse<User> response = new SearchResponseImpl(users, request.getPage(), request.getPageSize(), Long.valueOf(totalNumber).intValue(), hasNextPage);
return response;
}
@ -119,10 +120,10 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
User user = fillUser(userName, document);
users.add(user);
});
if (users.size()==1){
if (users.size() == 1) {
return users.get(0);
}else {
throw new SecurityManagementException("Unknown identifier "+identifier);
} else {
return new UserImpl(identifier);
}
}
@ -146,30 +147,83 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
groups.set((ArrayList) document.get("userGroups"));
List<Role> roleList = new ArrayList<>();
for (DBRef dbRef : roles.get()) {
Document roleDocument = Utils.getDocumentFromRef(dbRef,database);
Document roleDocument = Utils.getDocumentFromRef(dbRef, database);
Role role = new RoleImpl(roleDocument.getString("name"));
roleList.add(role);
}
List<Group> groupList = new ArrayList<>();
for (DBRef dbRef : groups.get()) {
Document groupDocument = Utils.getDocumentFromRef(dbRef,database);
Document groupDocument = Utils.getDocumentFromRef(dbRef, database);
Group group = new GroupImpl(groupDocument.getString("name"));
groupList.add(group);
}
User user = new UserImpl(userName,roleList,groupList);
User user = new UserImpl(userName, roleList, groupList);
return user;
}
@Override
public User create(User entity) throws SecurityManagementException {
save(entity, true);
return entity;
}
@Override
public User update(User entity) throws SecurityManagementException {
save(entity, false);
return entity;
}
private void save(User entity, boolean isCreated) throws SecurityManagementException {
MongoCollection<Document> userCollection = database.getCollection("user");
MongoCollection<Document> userGroupsCollection = database.getCollection("userGroups");
MongoCollection<Document> userRolesCollection = database.getCollection("userRoles");
AtomicReference<ArrayList<DBRef>> roles = new AtomicReference<>(new ArrayList<>());
AtomicReference<ArrayList<DBRef>> groups = new AtomicReference<>(new ArrayList<>());
List<Document> users = new ArrayList<>();
if (isCreated) {
userCollection.find(eq("login", entity.getIdentifier())).forEach((Block<? super Document>) document -> {
throw new SecurityManagementException("Existing identifier " + entity.getIdentifier());
});
} else {
userCollection.find(eq("login", entity.getIdentifier())).forEach((Block<? super Document>) document -> {
users.add(document);
});
if (users.size() == 0) {
throw new SecurityManagementException("unknown identifier " + entity.getIdentifier());
}
if (users.size() > 1) {
throw new SecurityManagementException("existing multiple times with identifier " + entity.getIdentifier());
}
}
for (Group group : entity.getGroups()) {
userGroupsCollection.find(eq("name", group.getName())).forEach((Block<? super Document>) document -> {
DBRef dbRef = new DBRef("userGroups", document.get("_id"));
groups.get().add(dbRef);
});
}
for (Role role : entity.getRoles()) {
userRolesCollection.find(eq("name", role.getName())).forEach((Block<? super Document>) document -> {
DBRef dbRef = new DBRef("userRoles", document.get("_id"));
roles.get().add(dbRef);
});
}
Document userDocument = new Document("_id", new ObjectId());
userDocument.append("login", entity.getIdentifier());
userDocument.append("password", entity.getIdentifier());
userDocument.append("userRoles", roles);
userDocument.append("userGroups", groups);
if (isCreated) {
userCollection.insertOne(userDocument);
} else {
userCollection.replaceOne(eq("login", entity.getIdentifier()), userDocument);
}
}
@Override
public void delete(String... identifiers) throws SecurityManagementException {
@ -208,6 +262,12 @@ public class KiePlatformUserManager implements UserManager, ContextualManager {
@Override
public void changePassword(String username,
String newPassword) throws SecurityManagementException {
MongoCollection<Document> userCollection = database.getCollection("user");
userCollection.find(eq("login", username)).forEach((Block<? super Document>) document -> {
document.append("password", newPassword);
userCollection.replaceOne(eq("login", username), document);
});
}

View file

@ -5,21 +5,16 @@ import org.chtijbug.guvnor.server.jaxrs.api.UserLoginInformation;
import org.chtijbug.guvnor.server.jaxrs.jaxb.Asset;
import org.chtijbug.guvnor.server.jaxrs.jaxb.Package;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectResponse;
import org.guvnor.common.services.project.model.Module;
import org.chtijbug.kie.rest.backend.service.AssetService;
import org.guvnor.common.services.project.model.WorkspaceProject;
import org.guvnor.common.services.project.service.WorkspaceProjectService;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.guvnor.structure.repositories.Branch;
import org.guvnor.structure.repositories.PublicURI;
import org.guvnor.structure.repositories.Repository;
import org.guvnor.structure.repositories.RepositoryService;
import org.kie.workbench.common.screens.datamodeller.model.EditorModelContent;
import org.kie.workbench.common.screens.datamodeller.service.DataModelerService;
import org.kie.workbench.common.services.datamodeller.core.DataObject;
import org.kie.workbench.common.services.datamodeller.core.impl.DataModelImpl;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.vfs.PathFactory;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.base.options.CommentedOption;
import org.uberfire.java.nio.file.DirectoryStream;
@ -29,15 +24,13 @@ import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.core.*;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.FileAlreadyExistsException;
import java.util.*;
@Path("/chtijbug")
@Named
@ApplicationScoped
@ -54,28 +47,25 @@ public class PackageResource {
@Inject
@Named("ioStrategy")
private IOService ioService;
@Inject
private OrganizationalUnitService organizationalUnitService;
@Inject
private RepositoryService repositoryService;
@Inject
private WorkspaceProjectService projectService;
private RestTypeDefinition dotFileFilter = new RestTypeDefinition();
@Inject
private DataModelerService dataModelerService;
@Inject
private WorkspaceProjectService workspaceProjectService;
@Inject
private AssetService assetService;
public PackageResource() {
System.out.println("coucou");
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/login")
@ -89,87 +79,18 @@ public class PackageResource {
userLoginInformation.getRoles().add(role);
}
}
userLoginInformation.setProjects(getAllProjects());
userLoginInformation.setProjects(assetService.getAllProjects());
return userLoginInformation;
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/detailedSpaces")
// @RolesAllowed({REST_ROLE, REST_PROJECT_ROLE})
public Collection<PlatformProjectResponse> getProjects() {
logger.debug("-----getSpaces--- ");
return getAllProjects();
}
private List<PlatformProjectResponse> getAllProjects() {
final List<PlatformProjectResponse> spaces = new ArrayList<>();
for (OrganizationalUnit ou : organizationalUnitService.getOrganizationalUnits()) {
spaces.addAll(getSpace(ou));
}
return spaces;
}
private List<PlatformProjectResponse> getSpace(OrganizationalUnit ou) {
final List<PlatformProjectResponse> repoNames = new ArrayList<>();
for (WorkspaceProject workspaceProject : workspaceProjectService.getAllWorkspaceProjects(ou)) {
for (Branch branch : workspaceProject.getRepository().getBranches()){
repoNames.add(getProjectResponse(workspaceProject,branch));
}
}
return repoNames;
}
private void toto() {
}
private PlatformProjectResponse getProjectResponse(WorkspaceProject workspaceProject,Branch branch) {
final PlatformProjectResponse projectResponse = new PlatformProjectResponse();
projectResponse.setName(workspaceProject.getName());
projectResponse.setSpaceName(workspaceProject.getOrganizationalUnit().getName());
if (workspaceProject.getMainModule() != null) {
Module kmodule = workspaceProject.getMainModule();
org.uberfire.backend.vfs.Path importVFPath = PathFactory.newPath("project.imports", branch.getPath().toURI()+"project.imports");
EditorModelContent econtent = dataModelerService.loadContent(importVFPath);
//EditorModelContent econtent = dataModelerService.loadContent(((KieModule) kmodule).getImportsPath());
DataModelImpl econtentDataModel = (DataModelImpl) econtent.getDataModel();
List<DataObject> dataObjects = econtentDataModel.getExternalClasses();
for (DataObject dataObject : dataObjects) {
System.out.println(dataObject.toString());
String className = "class=" + dataObject.getPackageName() + "." + dataObject.getName();
projectResponse.getJavaClasses().add(className);
}
projectResponse.setArtifactId(workspaceProject.getMainModule().getPom().getGav().getArtifactId());
projectResponse.setGroupId(workspaceProject.getMainModule().getPom().getGav().getGroupId());
projectResponse.setVersion(workspaceProject.getMainModule().getPom().getGav().getVersion());
projectResponse.setDescription(workspaceProject.getMainModule().getPom().getDescription());
projectResponse.setBranch(branch.getName());
}
final ArrayList<org.guvnor.rest.client.PublicURI> publicURIs = new ArrayList<>();
for (PublicURI publicURI : workspaceProject.getRepository().getPublicURIs()) {
final org.guvnor.rest.client.PublicURI responseURI = new org.guvnor.rest.client.PublicURI();
responseURI.setProtocol(publicURI.getProtocol());
responseURI.setUri(publicURI.getURI());
publicURIs.add(responseURI);
}
projectResponse.setPublicURIs(publicURIs);
return projectResponse;
return assetService.getAllProjects();
}
@GET
@ -206,12 +127,12 @@ public class PackageResource {
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName) {
try {
List<Asset> contentList = new LinkedList<>();
WorkspaceProject project = getProject(organizationalUnitName, projectName);
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPath = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
getContent(directoryStream, contentList);
assetService.getContent(directoryStream, contentList);
}
@ -221,118 +142,6 @@ public class PackageResource {
}
}
private WorkspaceProject getProject(String organizationalUnitName, String projectName) {
OrganizationalUnit organizationalUnit = organizationalUnitService.getOrganizationalUnit(organizationalUnitName);
Collection<WorkspaceProject> workspaceProjects = projectService.getAllWorkspaceProjects(organizationalUnit);
for (WorkspaceProject project : workspaceProjects) {
if (project.getName().equals(projectName)) {
return project;
}
}
// }
//}
return null;
}
private void getContentSource(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, Asset asset, List<org.uberfire.java.nio.file.Path> pathLinkedList) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
getContentSource(adirectoryStream, asset, pathLinkedList);
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())) {
Map<String, Object> listAttributes = ioService.readAttributes(elementPath);
if (asset.getTitle().equals(elementPath.getFileName().toString())) {
pathLinkedList.add(elementPath);
}
}
}
}
}
private void getContent(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, Collection<Asset> contentList) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
getContent(adirectoryStream, contentList);
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())) {
Map<String, Object> listAttributes = ioService.readAttributes(elementPath);
Asset asset = new Asset();
asset.setTitle(elementPath.getFileName().toString());
asset.setDirectory(elementPath.getParent().toString());
asset.setRefLink(elementPath.getFileName().toUri());
contentList.add(asset);
}
}
}
}
private String getContentSource(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
String result = getContentSource(adirectoryStream, assetName);
if (result != null && result.length() > 0) {
return result;
}
} else {
if (elementPath.getFileName().toString().startsWith(".") == false) {
if (elementPath.getFileName().toString().equals(assetName)) {
return ioService.readAllString(elementPath);
}
}
}
}
return null;
}
private org.uberfire.java.nio.file.Path getFileElementPath(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
org.uberfire.java.nio.file.Path foundElementPath = getFileElementPath(adirectoryStream, assetName);
if (foundElementPath != null) {
return foundElementPath;
}
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())
&& elementPath.getFileName().toString().contains(assetName)) {
return elementPath;
}
}
}
return null;
}
private org.uberfire.java.nio.file.Path getDirectoryElementPath(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream=null;
try {
adirectoryStream = ioService.newDirectoryStream(elementPath);
if (elementPath.getFileName().toString().equals(assetName)) {
return elementPath;
}
org.uberfire.java.nio.file.Path foundElementPath = getDirectoryElementPath(adirectoryStream, assetName);
if (foundElementPath != null) {
return foundElementPath;
}
}catch (Exception e){
}finally {
if (adirectoryStream!= null){
adirectoryStream.close();
}
}
}
}
return null;
}
@GET
@Path("{organizationalUnitName}/{projectName}/assets/{assetName}")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@ -340,13 +149,13 @@ public class PackageResource {
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, @PathParam("assetName") String assetName) {
List<Asset> resultList = new LinkedList<>();
try {
WorkspaceProject project = getProject(organizationalUnitName, projectName);
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
List<Asset> contentList = new LinkedList<>();
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPath = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
getContent(directoryStream, contentList);
assetService.getContent(directoryStream, contentList);
for (Asset asset : contentList) {
if (asset.getTitle().equals(assetName)) {
resultList.add(asset);
@ -368,12 +177,12 @@ public class PackageResource {
List<Asset> resultList = new LinkedList<>();
String result = "";
try {
WorkspaceProject project = getProject(organizationalUnitName, projectName);
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPath = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
result = getContentSource(directoryStream, assetName);
result = assetService.getContentSource(directoryStream, assetName);
}
return result;
} catch (RuntimeException e) {
@ -385,10 +194,10 @@ public class PackageResource {
@PUT
@Path("{organizationalUnitName}/{projectName}/asset/{assetName}")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public void updateAssetFromJAXB(
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName,
@PathParam("assetName") String assetName, String asset) {
updateAssetContent(organizationalUnitName, projectName, assetName, asset);
public Response updateAssetFromJAXB(@Context HttpHeaders headers,
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName,
@PathParam("assetName") String assetName, String asset) {
return updateAssetContent(headers, organizationalUnitName, projectName, assetName, asset, true);
}
@POST
@ -398,15 +207,15 @@ public class PackageResource {
public Asset createAssetFromSourceAndJAXB(
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, Asset asset) {
try {
WorkspaceProject project = getProject(organizationalUnitName, projectName);
if (project!= null) {
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPathDirectory = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream=null;
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = null;
try {
directoryStream = ioService.newDirectoryStream(nioPathDirectory);
org.uberfire.java.nio.file.Path directoryWhereCreateAsset = getDirectoryElementPath(directoryStream, asset.getTitle());
if (directoryWhereCreateAsset!= null) {
directoryStream = ioService.newDirectoryStream(nioPathDirectory);
org.uberfire.java.nio.file.Path directoryWhereCreateAsset = assetService.getDirectoryElementPath(directoryStream, asset.getTitle());
if (directoryWhereCreateAsset != null) {
final org.uberfire.java.nio.file.Path nioPath = Paths.get(directoryWhereCreateAsset.toUri());
if (ioService.exists(nioPath)) {
throw new FileAlreadyExistsException(nioPath.toString());
@ -414,10 +223,10 @@ public class PackageResource {
CommentedOption commentedOption = new CommentedOption(asset.getComment());
ioService.write(nioPath, asset.getContent().getBytes(), commentedOption);
}
}catch (Exception e){
} catch (Exception e) {
}finally {
if (directoryStream!= null){
} finally {
if (directoryStream != null) {
directoryStream.close();
}
}
@ -433,14 +242,64 @@ public class PackageResource {
@POST
@Path("{organizationalUnitName}/{projectName}/asset/{assetName}/source")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
public void updateAssetSource(
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, @PathParam("assetName") String assetName, String content) {
updateAssetContent(organizationalUnitName, projectName, assetName, content);
public Response createAssetSource(@Context HttpHeaders headers,
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, @PathParam("assetName") String assetName, String content) {
return updateAssetContent(headers, organizationalUnitName, projectName, assetName, content, true);
}
private void updateAssetContent(String organizationalUnitName, String projectName, String assetName, String content) {
@PUT
@Path("{organizationalUnitName}/{projectName}/asset/{assetName}/source")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
public Response updateAssetSource(@Context HttpHeaders headers,
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, @PathParam("assetName") String assetName, String content) {
return updateAssetContent(headers, organizationalUnitName, projectName, assetName, content, false);
}
@DELETE
@Path("{organizationalUnitName}/{projectName}/asset/{assetName}/source")
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
public Response deleteAssetSource(@Context HttpHeaders headers,
@PathParam("organizationalUnitName") String organizationalUnitName, @PathParam("projectName") String projectName, @PathParam("assetName") String assetName, String content) {
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
// Optional<Branch> rr = project.getRepository().getBranch("ee");
// org.uberfire.backend.vfs.Path tata = rr.get().getPath();
org.uberfire.backend.vfs.Path rootPath = project.getRootPath();
org.uberfire.java.nio.file.Path nioPath = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
org.uberfire.java.nio.file.Path elementToDelete = assetService.getFileElementPath(directoryStream, assetName);
if (elementToDelete == null) {
return Response.status(Response.Status.NOT_FOUND).build();
} else {
File fileToUpdate = elementToDelete.toFile();
if (fileToUpdate.isFile()) {
content = content.replace("\"", "");
ioService.delete(elementToDelete);
logger.debug("Returning OK response with content '{}'", content);
return Response.status(Response.Status.NO_CONTENT).build();
} else {
return Response.status(Response.Status.NOT_MODIFIED).entity("Asset is not a file").build();
}
}
} else {
logger.info("Project {} or Organization {} not found ", projectName, organizationalUnitName);
return Response.status(Response.Status.NOT_FOUND).entity("Project or Organization not found").build();
}
}
private Response updateAssetContent(HttpHeaders headers, String organizationalUnitName, String projectName, String assetName, String content, boolean isCreate) {
try {
WorkspaceProject project = getProject(organizationalUnitName, projectName);
WorkspaceProject project = assetService.getProject(organizationalUnitName, projectName);
if (project != null) {
// Optional<Branch> rr = project.getRepository().getBranch("ee");
@ -449,23 +308,43 @@ public class PackageResource {
org.uberfire.java.nio.file.Path nioPath = Paths.get(rootPath.toURI());
DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream = ioService.newDirectoryStream(nioPath);
org.uberfire.java.nio.file.Path elementToUpdate = getFileElementPath(directoryStream, assetName);
if (elementToUpdate != null) {
org.uberfire.java.nio.file.Path elementToUpdate = assetService.getFileElementPath(directoryStream, assetName);
if (elementToUpdate != null && isCreate) {
return Response.status(Response.Status.CONFLICT).build();
} else if (elementToUpdate != null && !isCreate) {
File fileToUpdate = elementToUpdate.toFile();
if (fileToUpdate.isFile()) {
content = content.replace("\"", "");
ioService.write(elementToUpdate, content);
// FileOutputStream fileOutputStream = new FileOutputStream(fileToUpdate);
// fileOutputStream.write(content.getBytes());
// fileOutputStream.close();
logger.debug("Returning OK response with content '{}'", content);
return Response.status(Response.Status.ACCEPTED).build();
} else {
return Response.status(Response.Status.NOT_MODIFIED).entity("Asset is not a file").build();
}
} else {//
if (isCreate) {
org.uberfire.java.nio.file.Path directoryWhereCreateAsset = assetService.getRuleDirectory(directoryStream, assetName);
if (directoryWhereCreateAsset != null) {
URI parentURI = directoryWhereCreateAsset.getParent().toUri();
URI uri = new URI(parentURI.getScheme(), parentURI.getUserInfo(), parentURI.getHost(), parentURI.getPort(), parentURI.getPath() + "/" + assetName, parentURI.getQuery(), parentURI.getFragment());
final org.uberfire.java.nio.file.Path nioPathWhere = Paths.get(uri);
CommentedOption commentedOption = new CommentedOption("Created from rest");
ioService.write(nioPathWhere, content.getBytes(), commentedOption);
return Response.status(Response.Status.CREATED).build();
} else {
return Response.status(Response.Status.NOT_FOUND).entity("no Rule package").build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("Asset not found").build();
}
}
}else{
throw new WebApplicationException("Asset not found " + assetName);
} else {
logger.info("Project {} or Organization {} not found ", projectName, organizationalUnitName);
return Response.status(Response.Status.NOT_FOUND).entity("Project or Organization not found").build();
}
} catch (RuntimeException e) {
throw new WebApplicationException(e);
} catch (RuntimeException | URISyntaxException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e).build();
}
}

View file

@ -44,6 +44,45 @@ public class RestTypeDefinition {
|| fileName.endsWith("." + ResourceType.FEEL.getDefaultExtension())
) {
result = true;
}
}
return result;
}
public boolean acceptDroolsFile(String fileName) {
boolean result = false;
if (fileName.startsWith(".") == false) {
if (fileName.endsWith("." + ResourceType.DRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.GDRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.RDRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.XDRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DSL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DSLR.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.RDSLR.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DRF.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.BPMN2.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.CMMN.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DTABLE.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.BRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.XSD.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.PMML.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DESCR.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.SCARD.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.TDRL.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.BAYES.getDefaultExtension())
// ||fileName.endsWith("." + ResourceType.JAVA.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.TEMPLATE.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DRT.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.GDST.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.SCGD.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.SOLVER.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.DMN.getDefaultExtension())
|| fileName.endsWith("." + ResourceType.FEEL.getDefaultExtension())
) {
result = true;
}

View file

@ -0,0 +1,262 @@
package org.chtijbug.kie.rest.backend.service;
import org.chtijbug.guvnor.server.jaxrs.jaxb.Asset;
import org.chtijbug.guvnor.server.jaxrs.model.PlatformProjectResponse;
import org.chtijbug.kie.rest.backend.RestTypeDefinition;
import org.guvnor.common.services.project.model.Module;
import org.guvnor.common.services.project.model.WorkspaceProject;
import org.guvnor.common.services.project.service.WorkspaceProjectService;
import org.guvnor.structure.organizationalunit.OrganizationalUnit;
import org.guvnor.structure.organizationalunit.OrganizationalUnitService;
import org.guvnor.structure.repositories.Branch;
import org.guvnor.structure.repositories.PublicURI;
import org.guvnor.structure.repositories.RepositoryService;
import org.jboss.errai.bus.server.annotations.Service;
import org.kie.workbench.common.screens.datamodeller.model.EditorModelContent;
import org.kie.workbench.common.screens.datamodeller.service.DataModelerService;
import org.kie.workbench.common.services.datamodeller.core.DataObject;
import org.kie.workbench.common.services.datamodeller.core.impl.DataModelImpl;
import org.slf4j.LoggerFactory;
import org.uberfire.backend.vfs.PathFactory;
import org.uberfire.io.IOService;
import org.uberfire.java.nio.file.DirectoryStream;
import org.uberfire.java.nio.file.Path;
import javax.inject.Inject;
import javax.inject.Named;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@Service
public class AssetService {
private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AssetService.class);
@Context
protected UriInfo uriInfo;
@Context
protected SecurityContext sc;
@Inject
@Named("ioStrategy")
private IOService ioService;
@Inject
private OrganizationalUnitService organizationalUnitService;
@Inject
private RepositoryService repositoryService;
@Inject
private WorkspaceProjectService projectService;
private RestTypeDefinition dotFileFilter = new RestTypeDefinition();
@Inject
private DataModelerService dataModelerService;
@Inject
private WorkspaceProjectService workspaceProjectService;
public List<PlatformProjectResponse> getAllProjects() {
final List<PlatformProjectResponse> spaces = new ArrayList<>();
for (OrganizationalUnit ou : organizationalUnitService.getOrganizationalUnits()) {
spaces.addAll(getSpace(ou));
}
return spaces;
}
private List<PlatformProjectResponse> getSpace(OrganizationalUnit ou) {
final List<PlatformProjectResponse> repoNames = new ArrayList<>();
for (WorkspaceProject workspaceProject : workspaceProjectService.getAllWorkspaceProjects(ou)) {
for (Branch branch : workspaceProject.getRepository().getBranches()) {
repoNames.add(getProjectResponse(workspaceProject, branch));
}
}
return repoNames;
}
private PlatformProjectResponse getProjectResponse(WorkspaceProject workspaceProject, Branch branch) {
final PlatformProjectResponse projectResponse = new PlatformProjectResponse();
projectResponse.setName(workspaceProject.getName());
projectResponse.setSpaceName(workspaceProject.getOrganizationalUnit().getName());
if (workspaceProject.getMainModule() != null) {
Module kmodule = workspaceProject.getMainModule();
org.uberfire.backend.vfs.Path importVFPath = PathFactory.newPath("project.imports", branch.getPath().toURI() + "project.imports");
EditorModelContent econtent = dataModelerService.loadContent(importVFPath);
//EditorModelContent econtent = dataModelerService.loadContent(((KieModule) kmodule).getImportsPath());
DataModelImpl econtentDataModel = (DataModelImpl) econtent.getDataModel();
List<DataObject> dataObjects = econtentDataModel.getExternalClasses();
for (DataObject dataObject : dataObjects) {
System.out.println(dataObject.toString());
String className = "class=" + dataObject.getPackageName() + "." + dataObject.getName();
projectResponse.getJavaClasses().add(className);
}
projectResponse.setArtifactId(workspaceProject.getMainModule().getPom().getGav().getArtifactId());
projectResponse.setGroupId(workspaceProject.getMainModule().getPom().getGav().getGroupId());
projectResponse.setVersion(workspaceProject.getMainModule().getPom().getGav().getVersion());
projectResponse.setDescription(workspaceProject.getMainModule().getPom().getDescription());
projectResponse.setBranch(branch.getName());
}
final ArrayList<org.guvnor.rest.client.PublicURI> publicURIs = new ArrayList<>();
for (PublicURI publicURI : workspaceProject.getRepository().getPublicURIs()) {
final org.guvnor.rest.client.PublicURI responseURI = new org.guvnor.rest.client.PublicURI();
responseURI.setProtocol(publicURI.getProtocol());
responseURI.setUri(publicURI.getURI());
publicURIs.add(responseURI);
}
projectResponse.setPublicURIs(publicURIs);
return projectResponse;
}
public WorkspaceProject getProject(String organizationalUnitName, String projectName) {
OrganizationalUnit organizationalUnit = organizationalUnitService.getOrganizationalUnit(organizationalUnitName);
if (organizationalUnit==null){
return null;
}
Collection<WorkspaceProject> workspaceProjects = projectService.getAllWorkspaceProjects(organizationalUnit);
if (workspaceProjects==null){
return null;
}
for (WorkspaceProject project : workspaceProjects) {
if (project.getName().equals(projectName)) {
return project;
}
}
// }
//}
return null;
}
private void getContentSource(DirectoryStream<Path> directoryStream, Asset asset, List<org.uberfire.java.nio.file.Path> pathLinkedList) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
getContentSource(adirectoryStream, asset, pathLinkedList);
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())) {
Map<String, Object> listAttributes = ioService.readAttributes(elementPath);
if (asset.getTitle().equals(elementPath.getFileName().toString())) {
pathLinkedList.add(elementPath);
}
}
}
}
}
public void getContent(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, Collection<Asset> contentList) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
getContent(adirectoryStream, contentList);
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())) {
Map<String, Object> listAttributes = ioService.readAttributes(elementPath);
Asset asset = new Asset();
asset.setTitle(elementPath.getFileName().toString());
asset.setDirectory(elementPath.getParent().toString());
asset.setRefLink(elementPath.getFileName().toUri());
contentList.add(asset);
}
}
}
}
public String getContentSource(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
String result = getContentSource(adirectoryStream, assetName);
if (result != null && result.length() > 0) {
return result;
}
} else {
if (elementPath.getFileName().toString().startsWith(".") == false) {
if (elementPath.getFileName().toString().equals(assetName)) {
return ioService.readAllString(elementPath);
}
}
}
}
return null;
}
public org.uberfire.java.nio.file.Path getFileElementPath(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
org.uberfire.java.nio.file.Path foundElementPath = getFileElementPath(adirectoryStream, assetName);
if (foundElementPath != null) {
return foundElementPath;
}
} else {
if (dotFileFilter.accept(elementPath.getFileName().toString())
&& elementPath.getFileName().toString().contains(assetName)) {
return elementPath;
}
}
}
return null;
}
public org.uberfire.java.nio.file.Path getRuleDirectory(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = ioService.newDirectoryStream(elementPath);
org.uberfire.java.nio.file.Path foundElementPath = getRuleDirectory(adirectoryStream, assetName);
if (foundElementPath != null) {
return foundElementPath;
}
} else {
if (dotFileFilter.acceptDroolsFile(elementPath.getFileName().toString())) {
return elementPath;
}
}
}
return null;
}
public org.uberfire.java.nio.file.Path getDirectoryElementPath(DirectoryStream<org.uberfire.java.nio.file.Path> directoryStream, String assetName) {
for (org.uberfire.java.nio.file.Path elementPath : directoryStream) {
if (org.uberfire.java.nio.file.Files.isDirectory(elementPath)) {
DirectoryStream<org.uberfire.java.nio.file.Path> adirectoryStream = null;
try {
adirectoryStream = ioService.newDirectoryStream(elementPath);
if (elementPath.getFileName().toString().equals(assetName)) {
return elementPath;
}
org.uberfire.java.nio.file.Path foundElementPath = getDirectoryElementPath(adirectoryStream, assetName);
if (foundElementPath != null) {
return foundElementPath;
}
} catch (Exception e) {
} finally {
if (adirectoryStream != null) {
adirectoryStream.close();
}
}
}
}
return null;
}
}