You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ambari.apache.org by al...@apache.org on 2015/02/24 17:32:02 UTC
[09/12] ambari git commit: AMBARI-9676. Initial Hive View Submission
to Contrib (alexantonenko)
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceManager.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceManager.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceManager.java
new file mode 100644
index 0000000..31d9e23
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceManager.java
@@ -0,0 +1,64 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.resources;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive.persistence.utils.FilteringStrategy;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ * Object that provides CRUD operations for resource objects
+ */
+public class FileResourceResourceManager extends PersonalCRUDResourceManager<FileResourceItem> {
+ private final static Logger LOG =
+ LoggerFactory.getLogger(FileResourceResourceManager.class);
+
+ /**
+ * Constructor
+ * @param context View Context instance
+ */
+ public FileResourceResourceManager(ViewContext context) {
+ super(FileResourceItem.class, context);
+ }
+
+ @Override
+ public FileResourceItem create(FileResourceItem object) {
+ return super.create(object);
+ }
+
+ @Override
+ public FileResourceItem read(Integer id) throws ItemNotFound {
+ return super.read(id);
+ }
+
+ @Override
+ public void delete(Integer resourceId) throws ItemNotFound {
+ super.delete(resourceId);
+ }
+
+ @Override
+ public List<FileResourceItem> readAll(FilteringStrategy filteringStrategy) {
+ return super.readAll(filteringStrategy);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceProvider.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceProvider.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceProvider.java
new file mode 100644
index 0000000..5b9fc65
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceResourceProvider.java
@@ -0,0 +1,107 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.resources;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.*;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Resource provider for resource
+ */
+public class FileResourceResourceProvider implements ResourceProvider<FileResourceItem> {
+ @Inject
+ ViewContext context;
+
+ protected FileResourceResourceManager resourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(FileResourceResourceProvider.class);
+
+ protected synchronized FileResourceResourceManager getResourceManager() {
+ if (resourceManager == null) {
+ resourceManager = new FileResourceResourceManager(context);
+ }
+ return resourceManager;
+ }
+
+ @Override
+ public FileResourceItem getResource(String resourceId, Set<String> properties) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ return getResourceManager().read(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ }
+
+ @Override
+ public Set<FileResourceItem> getResources(ReadRequest readRequest) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ return new HashSet<FileResourceItem>(getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())));
+ }
+
+ @Override
+ public void createResource(String s, Map<String, Object> stringObjectMap) throws SystemException, ResourceAlreadyExistsException, NoSuchResourceException, UnsupportedPropertyException {
+ FileResourceItem item = null;
+ try {
+ item = new FileResourceItem(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on creating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on creating resource", e);
+ }
+ getResourceManager().create(item);
+ }
+
+ @Override
+ public boolean updateResource(String resourceId, Map<String, Object> stringObjectMap) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ FileResourceItem item = null;
+ try {
+ item = new FileResourceItem(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on updating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on updating resource", e);
+ }
+ try {
+ getResourceManager().update(item, Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean deleteResource(String resourceId) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ getResourceManager().delete(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceService.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceService.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceService.java
new file mode 100644
index 0000000..2993280
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/resources/FileResourceService.java
@@ -0,0 +1,181 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.resources;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.ViewResourceHandler;
+import org.apache.ambari.view.hive.BaseService;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.utils.NotFoundFormattedException;
+import org.apache.ambari.view.hive.utils.ServiceFormattedException;
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import java.util.List;
+
+/**
+ * Servlet for Resources
+ * API:
+ * GET /:id
+ * read resource
+ * POST /
+ * create new resource
+ * GET /
+ * get all resource of current user
+ */
+public class FileResourceService extends BaseService {
+ @Inject
+ ViewResourceHandler handler;
+
+ protected FileResourceResourceManager resourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(FileResourceService.class);
+
+ protected synchronized FileResourceResourceManager getResourceManager() {
+ if (resourceManager == null) {
+ resourceManager = new FileResourceResourceManager(context);
+ }
+ return resourceManager;
+ }
+
+ /**
+ * Get single item
+ */
+ @GET
+ @Path("{id}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getOne(@PathParam("id") String id) {
+ try {
+ FileResourceItem FileResourceItem = null;
+ FileResourceItem = getResourceManager().read(Integer.valueOf(id));
+ JSONObject object = new JSONObject();
+ object.put("fileResource", FileResourceItem);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Delete single item
+ */
+ @DELETE
+ @Path("{id}")
+ public Response delete(@PathParam("id") String id) {
+ try {
+ getResourceManager().delete(Integer.valueOf(id));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Get all resources
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getList() {
+ try {
+ LOG.debug("Getting all resources");
+ List items = getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())); //TODO: move strategy to PersonalCRUDRM
+
+ JSONObject object = new JSONObject();
+ object.put("fileResources", items);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Update item
+ */
+ @PUT
+ @Path("{id}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response update(ResourceRequest request,
+ @PathParam("id") String id) {
+ try {
+ getResourceManager().update(request.fileResource, Integer.valueOf(id));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Create resource
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response create(ResourceRequest request, @Context HttpServletResponse response,
+ @Context UriInfo ui) {
+ try {
+ getResourceManager().create(request.fileResource);
+
+ FileResourceItem item = null;
+
+ item = getResourceManager().read(request.fileResource.getId());
+
+ response.setHeader("Location",
+ String.format("%s/%s", ui.getAbsolutePath().toString(), request.fileResource.getId()));
+
+ JSONObject object = new JSONObject();
+ object.put("fileResource", item);
+ return Response.ok(object).status(201).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Wrapper object for json mapping
+ */
+ public static class ResourceRequest {
+ public FileResourceItem fileResource;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQuery.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQuery.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQuery.java
new file mode 100644
index 0000000..fd75714
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQuery.java
@@ -0,0 +1,96 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.savedQueries;
+
+import org.apache.ambari.view.hive.persistence.utils.PersonalResource;
+import org.apache.commons.beanutils.BeanUtils;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Map;
+
+/**
+ * Bean to represent saved query
+ */
+public class SavedQuery implements Serializable, PersonalResource {
+ private String queryFile;
+ private String dataBase;
+ private String title;
+ private String shortQuery;
+
+ private Integer id;
+ private String owner;
+
+ public SavedQuery() {}
+ public SavedQuery(Map<String, Object> stringObjectMap) throws InvocationTargetException, IllegalAccessException {
+ BeanUtils.populate(this, stringObjectMap);
+ }
+
+ @Override
+ public Integer getId() {
+ return id;
+ }
+
+ @Override
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Override
+ public String getOwner() {
+ return owner;
+ }
+
+ @Override
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public String getQueryFile() {
+ return queryFile;
+ }
+
+ public void setQueryFile(String queryFile) {
+ this.queryFile = queryFile;
+ }
+
+ public String getDataBase() {
+ return dataBase;
+ }
+
+ public void setDataBase(String dataBase) {
+ this.dataBase = dataBase;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public String getShortQuery() {
+ return shortQuery;
+ }
+
+ public void setShortQuery(String shortQuery) {
+ this.shortQuery = shortQuery;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceManager.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceManager.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceManager.java
new file mode 100644
index 0000000..a3c0f1b
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceManager.java
@@ -0,0 +1,132 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.savedQueries;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive.persistence.utils.FilteringStrategy;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.apache.ambari.view.hive.utils.*;
+import org.apache.ambari.view.hive.utils.HdfsUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Object that provides CRUD operations for query objects
+ */
+public class SavedQueryResourceManager extends PersonalCRUDResourceManager<SavedQuery> {
+ private final static Logger LOG =
+ LoggerFactory.getLogger(SavedQueryResourceManager.class);
+
+ /**
+ * Constructor
+ * @param context View Context instance
+ */
+ private SavedQueryResourceManager(ViewContext context) {
+ super(SavedQuery.class, context);
+ }
+
+ //TODO: move all context-singletones to ContextController or smth like that
+ private static Map<String, SavedQueryResourceManager> viewSingletonObjects = new HashMap<String, SavedQueryResourceManager>();
+ public static SavedQueryResourceManager getInstance(ViewContext context) {
+ if (!viewSingletonObjects.containsKey(context.getInstanceName()))
+ viewSingletonObjects.put(context.getInstanceName(), new SavedQueryResourceManager(context));
+ return viewSingletonObjects.get(context.getInstanceName());
+ }
+ static Map<String, SavedQueryResourceManager> getViewSingletonObjects() {
+ return viewSingletonObjects;
+ }
+
+ @Override
+ public SavedQuery create(SavedQuery object) {
+ object = super.create(object);
+ try {
+
+ if (object.getQueryFile() == null || object.getQueryFile().isEmpty()) {
+ createDefaultQueryFile(object);
+ }
+
+ } catch (ServiceFormattedException e) {
+ cleanupAfterErrorAndThrowAgain(object, e);
+ }
+ return object;
+ }
+
+ private void createDefaultQueryFile(SavedQuery object) {
+ String userScriptsPath = context.getProperties().get("scripts.dir");
+ if (userScriptsPath == null) {
+ String msg = "scripts.dir is not configured!";
+ LOG.error(msg);
+ throw new MisconfigurationFormattedException("scripts.dir");
+ }
+
+ String normalizedName = String.format("hive-query-%d", object.getId());
+ String timestamp = new SimpleDateFormat("yyyy-MM-dd_hh-mm").format(new Date());
+ String baseFileName = String.format(userScriptsPath +
+ "/%s-%s", normalizedName, timestamp);
+
+ String newFilePath = HdfsUtil.findUnallocatedFileName(context, baseFileName, ".hql");
+ HdfsUtil.putStringToFile(context, newFilePath, "");
+
+ object.setQueryFile(newFilePath);
+ getStorage().store(SavedQuery.class, object);
+ }
+
+ @Override
+ public SavedQuery read(Integer id) throws ItemNotFound {
+ SavedQuery savedQuery = super.read(id);
+ fillShortQueryField(savedQuery);
+ return savedQuery;
+ }
+
+ private void fillShortQueryField(SavedQuery savedQuery) {
+ if (savedQuery.getQueryFile() != null) {
+ FilePaginator paginator = new FilePaginator(savedQuery.getQueryFile(), context);
+ String query = null;
+ try {
+ query = paginator.readPage(0);
+ } catch (IOException e) {
+ LOG.error("Can't read query file " + savedQuery.getQueryFile());
+ return;
+ } catch (InterruptedException e) {
+ LOG.error("Can't read query file " + savedQuery.getQueryFile());
+ return;
+ }
+ savedQuery.setShortQuery(query.substring(0, (query.length() > 42)?42:query.length()));
+ }
+ getStorage().store(SavedQuery.class, savedQuery);
+ }
+
+ @Override
+ public List<SavedQuery> readAll(FilteringStrategy filteringStrategy) {
+ return super.readAll(filteringStrategy);
+ }
+
+ @Override
+ public void delete(Integer resourceId) throws ItemNotFound {
+ super.delete(resourceId);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceProvider.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceProvider.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceProvider.java
new file mode 100644
index 0000000..20df9e6
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryResourceProvider.java
@@ -0,0 +1,104 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.savedQueries;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.*;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Resource provider for SavedQuery
+ */
+public class SavedQueryResourceProvider implements ResourceProvider<SavedQuery> {
+ @Inject
+ ViewContext context;
+
+ protected SavedQueryResourceManager resourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(SavedQueryResourceProvider.class);
+
+ protected synchronized SavedQueryResourceManager getResourceManager() {
+ return SavedQueryResourceManager.getInstance(context);
+ }
+
+ @Override
+ public SavedQuery getResource(String resourceId, Set<String> properties) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ return getResourceManager().read(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ }
+
+ @Override
+ public Set<SavedQuery> getResources(ReadRequest readRequest) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ return new HashSet<SavedQuery>(getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())));
+ }
+
+ @Override
+ public void createResource(String s, Map<String, Object> stringObjectMap) throws SystemException, ResourceAlreadyExistsException, NoSuchResourceException, UnsupportedPropertyException {
+ SavedQuery item = null;
+ try {
+ item = new SavedQuery(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on creating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on creating resource", e);
+ }
+ getResourceManager().create(item);
+ }
+
+ @Override
+ public boolean updateResource(String resourceId, Map<String, Object> stringObjectMap) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ SavedQuery item = null;
+ try {
+ item = new SavedQuery(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on updating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on updating resource", e);
+ }
+ try {
+ getResourceManager().update(item, Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean deleteResource(String resourceId) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ getResourceManager().delete(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryService.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryService.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryService.java
new file mode 100644
index 0000000..f6d5f41
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/savedQueries/SavedQueryService.java
@@ -0,0 +1,184 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.savedQueries;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.ViewResourceHandler;
+import org.apache.ambari.view.hive.BaseService;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.apache.ambari.view.hive.utils.NotFoundFormattedException;
+import org.apache.ambari.view.hive.utils.ServiceFormattedException;
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import java.util.List;
+
+/**
+ * Servlet for queries
+ * API:
+ * GET /:id
+ * read SavedQuery
+ * POST /
+ * create new SavedQuery
+ * Required: title, queryFile
+ * GET /
+ * get all SavedQueries of current user
+ */
+public class SavedQueryService extends BaseService {
+ @Inject
+ ViewResourceHandler handler;
+
+ protected SavedQueryResourceManager resourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(SavedQueryService.class);
+
+ protected synchronized SavedQueryResourceManager getResourceManager() {
+ return SavedQueryResourceManager.getInstance(context);
+ }
+
+ protected void setResourceManager(SavedQueryResourceManager resourceManager) {
+ this.resourceManager = resourceManager;
+ }
+
+ /**
+ * Get single item
+ */
+ @GET
+ @Path("{queryId}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getOne(@PathParam("queryId") String queryId) {
+ try {
+ SavedQuery savedQuery = null;
+ savedQuery = getResourceManager().read(Integer.valueOf(queryId));
+ JSONObject object = new JSONObject();
+ object.put("savedQuery", savedQuery);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Delete single item
+ */
+ @DELETE
+ @Path("{queryId}")
+ public Response delete(@PathParam("queryId") String queryId) {
+ try {
+ getResourceManager().delete(Integer.valueOf(queryId));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Get all SavedQueries
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getList() {
+ try {
+ LOG.debug("Getting all SavedQuery");
+ List allSavedQueries = getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())); //TODO: move strategy to PersonalCRUDRM
+
+ JSONObject object = new JSONObject();
+ object.put("savedQueries", allSavedQueries);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Update item
+ */
+ @PUT
+ @Path("{queryId}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response update(SavedQueryRequest request,
+ @PathParam("queryId") String queryId) {
+ try {
+ getResourceManager().update(request.savedQuery, Integer.valueOf(queryId));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Create savedQuery
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response create(SavedQueryRequest request, @Context HttpServletResponse response,
+ @Context UriInfo ui) {
+ try {
+ getResourceManager().create(request.savedQuery);
+
+ SavedQuery item = null;
+
+ item = getResourceManager().read(request.savedQuery.getId());
+
+ response.setHeader("Location",
+ String.format("%s/%s", ui.getAbsolutePath().toString(), request.savedQuery.getId()));
+
+ JSONObject object = new JSONObject();
+ object.put("savedQuery", item);
+ return Response.ok(object).status(201).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Wrapper object for json mapping
+ */
+ public static class SavedQueryRequest {
+ public SavedQuery savedQuery;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDF.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDF.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDF.java
new file mode 100644
index 0000000..4a58e38
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDF.java
@@ -0,0 +1,87 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.udfs;
+
+import org.apache.ambari.view.hive.persistence.utils.PersonalResource;
+import org.apache.commons.beanutils.BeanUtils;
+
+import java.io.Serializable;
+import java.lang.reflect.InvocationTargetException;
+import java.util.Map;
+
+/**
+ * Bean to represent UDF
+ */
+public class UDF implements Serializable, PersonalResource {
+ private String name;
+ private String classname;
+ private Integer fileResource;
+
+ private Integer id;
+ private String owner;
+
+ public UDF() {}
+ public UDF(Map<String, Object> stringObjectMap) throws InvocationTargetException, IllegalAccessException {
+ BeanUtils.populate(this, stringObjectMap);
+ }
+
+ @Override
+ public Integer getId() {
+ return id;
+ }
+
+ @Override
+ public void setId(Integer id) {
+ this.id = id;
+ }
+
+ @Override
+ public String getOwner() {
+ return owner;
+ }
+
+ @Override
+ public void setOwner(String owner) {
+ this.owner = owner;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public String getClassname() {
+ return classname;
+ }
+
+ public void setClassname(String classname) {
+ this.classname = classname;
+ }
+
+ public Integer getFileResource() {
+ return fileResource;
+ }
+
+ public void setFileResource(Integer fileResource) {
+ this.fileResource = fileResource;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceManager.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceManager.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceManager.java
new file mode 100644
index 0000000..cb4264f
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceManager.java
@@ -0,0 +1,64 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.udfs;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.ambari.view.hive.persistence.utils.FilteringStrategy;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.List;
+
+/**
+ * Object that provides CRUD operations for udf objects
+ */
+public class UDFResourceManager extends PersonalCRUDResourceManager<UDF> {
+ private final static Logger LOG =
+ LoggerFactory.getLogger(UDFResourceManager.class);
+
+ /**
+ * Constructor
+ * @param context View Context instance
+ */
+ public UDFResourceManager(ViewContext context) {
+ super(UDF.class, context);
+ }
+
+ @Override
+ public UDF read(Integer id) throws ItemNotFound {
+ return super.read(id);
+ }
+
+ @Override
+ public List<UDF> readAll(FilteringStrategy filteringStrategy) {
+ return super.readAll(filteringStrategy);
+ }
+
+ @Override
+ public UDF create(UDF object) {
+ return super.create(object);
+ }
+
+ @Override
+ public void delete(Integer resourceId) throws ItemNotFound {
+ super.delete(resourceId);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceProvider.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceProvider.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceProvider.java
new file mode 100644
index 0000000..70994eb
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFResourceProvider.java
@@ -0,0 +1,107 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.udfs;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.*;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.lang.reflect.InvocationTargetException;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Resource provider for udf
+ */
+public class UDFResourceProvider implements ResourceProvider<UDF> {
+ @Inject
+ ViewContext context;
+
+ protected UDFResourceManager resourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(UDFResourceProvider.class);
+
+ protected synchronized UDFResourceManager getResourceManager() {
+ if (resourceManager == null) {
+ resourceManager = new UDFResourceManager(context);
+ }
+ return resourceManager;
+ }
+
+ @Override
+ public UDF getResource(String resourceId, Set<String> properties) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ return getResourceManager().read(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ }
+
+ @Override
+ public Set<UDF> getResources(ReadRequest readRequest) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ return new HashSet<UDF>(getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())));
+ }
+
+ @Override
+ public void createResource(String s, Map<String, Object> stringObjectMap) throws SystemException, ResourceAlreadyExistsException, NoSuchResourceException, UnsupportedPropertyException {
+ UDF item = null;
+ try {
+ item = new UDF(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on creating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on creating resource", e);
+ }
+ getResourceManager().create(item);
+ }
+
+ @Override
+ public boolean updateResource(String resourceId, Map<String, Object> stringObjectMap) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ UDF item = null;
+ try {
+ item = new UDF(stringObjectMap);
+ } catch (InvocationTargetException e) {
+ throw new SystemException("error on updating resource", e);
+ } catch (IllegalAccessException e) {
+ throw new SystemException("error on updating resource", e);
+ }
+ try {
+ getResourceManager().update(item, Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+
+ @Override
+ public boolean deleteResource(String resourceId) throws SystemException, NoSuchResourceException, UnsupportedPropertyException {
+ try {
+ getResourceManager().delete(Integer.valueOf(resourceId));
+ } catch (ItemNotFound itemNotFound) {
+ throw new NoSuchResourceException(resourceId);
+ }
+ return true;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFService.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFService.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFService.java
new file mode 100644
index 0000000..864d5b0
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/resources/udfs/UDFService.java
@@ -0,0 +1,196 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.resources.udfs;
+
+import com.google.inject.Inject;
+import org.apache.ambari.view.ViewResourceHandler;
+import org.apache.ambari.view.hive.BaseService;
+import org.apache.ambari.view.hive.persistence.utils.ItemNotFound;
+import org.apache.ambari.view.hive.persistence.utils.OnlyOwnersFilteringStrategy;
+import org.apache.ambari.view.hive.resources.PersonalCRUDResourceManager;
+import org.apache.ambari.view.hive.resources.resources.FileResourceItem;
+import org.apache.ambari.view.hive.resources.resources.FileResourceResourceManager;
+import org.apache.ambari.view.hive.utils.NotFoundFormattedException;
+import org.apache.ambari.view.hive.utils.ServiceFormattedException;
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.*;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import java.util.List;
+
+/**
+ * Servlet for UDFs
+ * API:
+ * GET /:id
+ * read udf
+ * POST /
+ * create new udf
+ * GET /
+ * get all udf of current user
+ */
+public class UDFService extends BaseService {
+ @Inject
+ ViewResourceHandler handler;
+
+ protected UDFResourceManager resourceManager = null;
+ protected FileResourceResourceManager fileResourceResourceManager = null;
+ protected final static Logger LOG =
+ LoggerFactory.getLogger(UDFService.class);
+
+ protected synchronized UDFResourceManager getResourceManager() {
+ if (resourceManager == null) {
+ resourceManager = new UDFResourceManager(context);
+ }
+ return resourceManager;
+ }
+
+ protected synchronized FileResourceResourceManager getFileResourceResourceManager() {
+ if (fileResourceResourceManager == null) {
+ fileResourceResourceManager = new FileResourceResourceManager(context);
+ }
+ return fileResourceResourceManager;
+ }
+
+ /**
+ * Get single item
+ */
+ @GET
+ @Path("{id}")
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getOne(@PathParam("id") String id) {
+ try {
+ UDF UDF = null;
+ UDF = getResourceManager().read(Integer.valueOf(id));
+ JSONObject object = new JSONObject();
+ object.put("udf", UDF);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Delete single item
+ */
+ @DELETE
+ @Path("{id}")
+ public Response delete(@PathParam("id") String id) {
+ try {
+ getResourceManager().delete(Integer.valueOf(id));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Get all UDFs
+ */
+ @GET
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response getList() {
+ try {
+ LOG.debug("Getting all udf");
+ List items = getResourceManager().readAll(
+ new OnlyOwnersFilteringStrategy(this.context.getUsername())); //TODO: move strategy to PersonalCRUDRM
+
+ JSONObject object = new JSONObject();
+ object.put("udfs", items);
+ return Response.ok(object).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Update item
+ */
+ @PUT
+ @Path("{id}")
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response update(UDFRequest request,
+ @PathParam("id") String id) {
+ try {
+ if (request.udf.getFileResource() != null)
+ getFileResourceResourceManager().read(request.udf.getFileResource());
+ getResourceManager().update(request.udf, Integer.valueOf(id));
+ return Response.status(204).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Create udf
+ */
+ @POST
+ @Consumes(MediaType.APPLICATION_JSON)
+ public Response create(UDFRequest request, @Context HttpServletResponse response,
+ @Context UriInfo ui) {
+ try {
+ if (request.udf.getFileResource() != null)
+ getFileResourceResourceManager().read(request.udf.getFileResource());
+ getResourceManager().create(request.udf);
+
+ UDF item = null;
+
+ item = getResourceManager().read(request.udf.getId());
+
+ response.setHeader("Location",
+ String.format("%s/%s", ui.getAbsolutePath().toString(), request.udf.getId()));
+
+ JSONObject object = new JSONObject();
+ object.put("udf", item);
+ return Response.ok(object).status(201).build();
+ } catch (WebApplicationException ex) {
+ throw ex;
+ } catch (ItemNotFound itemNotFound) {
+ throw new NotFoundFormattedException(itemNotFound.getMessage(), itemNotFound);
+ } catch (Exception ex) {
+ throw new ServiceFormattedException(ex.getMessage(), ex);
+ }
+ }
+
+ /**
+ * Wrapper object for json mapping
+ */
+ public static class UDFRequest {
+ public UDF udf;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/BadRequestFormattedException.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/BadRequestFormattedException.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/BadRequestFormattedException.java
new file mode 100644
index 0000000..0641af1
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/BadRequestFormattedException.java
@@ -0,0 +1,27 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+public class BadRequestFormattedException extends ServiceFormattedException {
+ private final static int STATUS = 400;
+
+ public BadRequestFormattedException(String message, Throwable exception) {
+ super(message, exception, STATUS);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/FilePaginator.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/FilePaginator.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/FilePaginator.java
new file mode 100644
index 0000000..f27e1f9
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/FilePaginator.java
@@ -0,0 +1,127 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.hadoop.fs.FSDataInputStream;
+
+import java.io.IOException;
+import java.nio.charset.Charset;
+import java.util.Arrays;
+
+import static java.lang.Math.ceil;
+
+/**
+ * Pagination for HDFS file implementation
+ */
+public class FilePaginator {
+ public static int MB = 1024*1024;
+ public static int PAGE_SIZE = 1*MB;
+
+ private String filePath;
+ private HdfsApi hdfsApi;
+
+ /**
+ * Constructor
+ * @param filePath Path to file on HDFS
+ * @param context View Context instance
+ */
+ public FilePaginator(String filePath, ViewContext context) {
+ this.filePath = filePath;
+ hdfsApi = HdfsApi.getInstance(context);
+ }
+
+ /**
+ * Set page size
+ * @param PAGE_SIZE size
+ */
+ public static void setPageSize(int PAGE_SIZE) {
+ FilePaginator.PAGE_SIZE = PAGE_SIZE;
+ }
+
+ /**
+ * Get page count
+ * @return page count
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public long pageCount() throws IOException, InterruptedException {
+ return (long)
+ ceil( hdfsApi.getFileStatus(filePath).getLen() / ((double)PAGE_SIZE) );
+ }
+
+ /**
+ * Read one page of size PAGE_SIZE
+ * @param page page index
+ * @return data in UTF-8
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public String readPage(long page) throws IOException, InterruptedException {
+ FSDataInputStream stream = hdfsApi.open(filePath);
+ try {
+ stream.seek(page * PAGE_SIZE);
+ } catch (IOException e) {
+ throw new IllegalArgumentException("Page " + page + " does not exists");
+ }
+
+ byte[] buffer = new byte[PAGE_SIZE];
+ int readCount = 0;
+ int read = 0;
+ while(read < PAGE_SIZE) {
+ try {
+ readCount = stream.read(buffer, read, PAGE_SIZE-read);
+ } catch (IOException e) {
+ stream.close();
+ throw e;
+ }
+ if (readCount == -1)
+ break;
+ read += readCount;
+ }
+ if (read != 0) {
+ byte[] readData = Arrays.copyOfRange(buffer, 0, read);
+ return new String(readData, Charset.forName("UTF-8"));
+ } else {
+ if (page == 0) {
+ return "";
+ }
+ throw new IllegalArgumentException("Page " + page + " does not exists");
+ }
+ }
+
+ public String readFull(long sizeLimit) throws IOException, InterruptedException {
+ StringBuilder builder = new StringBuilder();
+ int i = 0;
+ while (true) {
+ try {
+ builder.append(readPage(i++));
+ } catch (IllegalArgumentException ex) {
+ break;
+ }
+ if (sizeLimit != -1 && (i+1)*PAGE_SIZE > sizeLimit)
+ break;
+ }
+ return builder.toString();
+ }
+
+ public String readFull() throws IOException, InterruptedException {
+ return readFull(-1);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsApi.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsApi.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsApi.java
new file mode 100644
index 0000000..9a120fa
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsApi.java
@@ -0,0 +1,399 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.*;
+import org.apache.hadoop.fs.permission.FsPermission;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
+import org.apache.hadoop.hdfs.web.WebHdfsFileSystem;
+import org.apache.hadoop.security.UserGroupInformation;
+import org.json.simple.JSONArray;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URI;
+import java.security.PrivilegedExceptionAction;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * HDFS Business Delegate
+ */
+public class HdfsApi {
+ private Configuration conf = new Configuration();
+
+ private FileSystem fs;
+ private Map<String, String> params;
+
+ private UserGroupInformation ugi;
+ private final static Logger LOG =
+ LoggerFactory.getLogger(HdfsApi.class);
+
+ /**
+ * Constructor
+ * @param defaultFs hdfs uri
+ * @param username user.name
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public HdfsApi(final String defaultFs, String username, Map<String, String> params) throws IOException,
+ InterruptedException {
+ this.params = params;
+ Thread.currentThread().setContextClassLoader(null);
+ conf.set("fs.hdfs.impl", DistributedFileSystem.class.getName());
+ conf.set("fs.webhdfs.impl", WebHdfsFileSystem.class.getName());
+ conf.set("fs.file.impl", "org.apache.hadoop.fs.LocalFileSystem");
+ ugi = UserGroupInformation.createProxyUser(username, getProxyUser());
+ fs = ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
+ public FileSystem run() throws IOException {
+ return FileSystem.get(URI.create(defaultFs), conf);
+ }
+ });
+ }
+
+ private UserGroupInformation getProxyUser() throws IOException {
+ UserGroupInformation proxyuser;
+ if (params.containsKey("proxyuser")) {
+ proxyuser = UserGroupInformation.createRemoteUser(params.get("proxyuser"));
+ } else {
+ proxyuser = UserGroupInformation.getCurrentUser();
+ }
+
+ proxyuser.setAuthenticationMethod(getAuthenticationMethod());
+ return proxyuser;
+ }
+
+ private UserGroupInformation.AuthenticationMethod getAuthenticationMethod() {
+ UserGroupInformation.AuthenticationMethod authMethod;
+ if (params.containsKey("auth")) {
+ authMethod = UserGroupInformation.AuthenticationMethod.valueOf(params.get("auth"));
+ } else {
+ authMethod = UserGroupInformation.AuthenticationMethod.SIMPLE;
+ }
+ return authMethod;
+ }
+
+ /**
+ * List dir operation
+ * @param path path
+ * @return array of FileStatus objects
+ * @throws java.io.FileNotFoundException
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public FileStatus[] listdir(final String path) throws FileNotFoundException,
+ IOException, InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<FileStatus[]>() {
+ public FileStatus[] run() throws FileNotFoundException, Exception {
+ return fs.listStatus(new Path(path));
+ }
+ });
+ }
+
+ /**
+ * Get file status
+ * @param path path
+ * @return file status
+ * @throws java.io.IOException
+ * @throws java.io.FileNotFoundException
+ * @throws InterruptedException
+ */
+ public FileStatus getFileStatus(final String path) throws IOException,
+ FileNotFoundException, InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<FileStatus>() {
+ public FileStatus run() throws FileNotFoundException, IOException {
+ return fs.getFileStatus(new Path(path));
+ }
+ });
+ }
+
+ /**
+ * Make directory
+ * @param path path
+ * @return success
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public boolean mkdir(final String path) throws IOException,
+ InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<Boolean>() {
+ public Boolean run() throws Exception {
+ return fs.mkdirs(new Path(path));
+ }
+ });
+ }
+
+ /**
+ * Rename
+ * @param src source path
+ * @param dst destination path
+ * @return success
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public boolean rename(final String src, final String dst) throws IOException,
+ InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<Boolean>() {
+ public Boolean run() throws Exception {
+ return fs.rename(new Path(src), new Path(dst));
+ }
+ });
+ }
+
+ /**
+ * Delete
+ * @param path path
+ * @param recursive delete recursive
+ * @return success
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public boolean delete(final String path, final boolean recursive)
+ throws IOException, InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<Boolean>() {
+ public Boolean run() throws Exception {
+ return fs.delete(new Path(path), recursive);
+ }
+ });
+ }
+
+ /**
+ * Home directory
+ * @return home directory
+ * @throws Exception
+ */
+ public Path getHomeDir() throws Exception {
+ return ugi.doAs(new PrivilegedExceptionAction<Path>() {
+ public Path run() throws IOException {
+ return fs.getHomeDirectory();
+ }
+ });
+ }
+
+ /**
+ * Hdfs Status
+ * @return home directory
+ * @throws Exception
+ */
+ public FsStatus getStatus() throws Exception {
+ return ugi.doAs(new PrivilegedExceptionAction<FsStatus>() {
+ public FsStatus run() throws IOException {
+ return fs.getStatus();
+ }
+ });
+ }
+
+ /**
+ * Create file
+ * @param path path
+ * @param overwrite overwrite existent file
+ * @return output stream
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public FSDataOutputStream create(final String path, final boolean overwrite)
+ throws IOException, InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<FSDataOutputStream>() {
+ public FSDataOutputStream run() throws Exception {
+ return fs.create(new Path(path), overwrite);
+ }
+ });
+ }
+
+ /**
+ * Open file
+ * @param path path
+ * @return input stream
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public FSDataInputStream open(final String path) throws IOException,
+ InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<FSDataInputStream>() {
+ public FSDataInputStream run() throws Exception {
+ return fs.open(new Path(path));
+ }
+ });
+ }
+
+ /**
+ * Copy file
+ * @param src source path
+ * @param dest destination path
+ * @return success
+ * @throws java.io.IOException
+ * @throws InterruptedException
+ */
+ public void copy(final String src, final String dest) throws IOException,
+ InterruptedException {
+ boolean result = ugi.doAs(new PrivilegedExceptionAction<Boolean>() {
+ public Boolean run() throws Exception {
+ return FileUtil.copy(fs, new Path(src), fs, new Path(dest), false, conf);
+ }
+ });
+ if (!result) {
+ throw new ServiceFormattedException("Can't copy source file from " + src + " to " + dest);
+ }
+ }
+
+ public boolean exists(final String newFilePath) throws IOException, InterruptedException {
+ return ugi.doAs(new PrivilegedExceptionAction<Boolean>() {
+ public Boolean run() throws Exception {
+ return fs.exists(new Path(newFilePath));
+ }
+ });
+ }
+
+ /**
+ * Converts a Hadoop permission into a Unix permission symbolic representation
+ * (i.e. -rwxr--r--) or default if the permission is NULL.
+ *
+ * @param p
+ * Hadoop permission.
+ * @return the Unix permission symbolic representation or default if the
+ * permission is NULL.
+ */
+ private static String permissionToString(FsPermission p) {
+ return (p == null) ? "default" : "-" + p.getUserAction().SYMBOL
+ + p.getGroupAction().SYMBOL + p.getOtherAction().SYMBOL;
+ }
+
+ /**
+ * Converts a Hadoop <code>FileStatus</code> object into a JSON array object.
+ * It replaces the <code>SCHEME://HOST:PORT</code> of the path with the
+ * specified URL.
+ * <p/>
+ *
+ * @param status
+ * Hadoop file status.
+ * @return The JSON representation of the file status.
+ */
+
+ public static Map<String, Object> fileStatusToJSON(FileStatus status) {
+ Map<String, Object> json = new LinkedHashMap<String, Object>();
+ json.put("path", status.getPath().toString());
+ json.put("isDirectory", status.isDirectory());
+ json.put("len", status.getLen());
+ json.put("owner", status.getOwner());
+ json.put("group", status.getGroup());
+ json.put("permission", permissionToString(status.getPermission()));
+ json.put("accessTime", status.getAccessTime());
+ json.put("modificationTime", status.getModificationTime());
+ json.put("blockSize", status.getBlockSize());
+ json.put("replication", status.getReplication());
+ return json;
+ }
+
+ /**
+ * Converts a Hadoop <code>FileStatus</code> array into a JSON array object.
+ * It replaces the <code>SCHEME://HOST:PORT</code> of the path with the
+ * specified URL.
+ * <p/>
+ *
+ * @param status
+ * Hadoop file status array.
+ * @return The JSON representation of the file status array.
+ */
+ @SuppressWarnings("unchecked")
+ public static JSONArray fileStatusToJSON(FileStatus[] status) {
+ JSONArray json = new JSONArray();
+ if (status != null) {
+ for (FileStatus s : status) {
+ json.add(fileStatusToJSON(s));
+ }
+ }
+ return json;
+ }
+
+
+ private static Map<String, HdfsApi> viewSingletonObjects = new HashMap<String, HdfsApi>();
+ /**
+ * Returns HdfsApi object specific to instance
+ * @param context View Context instance
+ * @return Hdfs business delegate object
+ */
+ public static HdfsApi getInstance(ViewContext context) {
+ if (!viewSingletonObjects.containsKey(context.getInstanceName()))
+ viewSingletonObjects.put(context.getInstanceName(), connectToHDFSApi(context));
+ return viewSingletonObjects.get(context.getInstanceName());
+ }
+
+ public static void setInstance(ViewContext context, HdfsApi api) {
+ viewSingletonObjects.put(context.getInstanceName(), api);
+ }
+
+ public static HdfsApi connectToHDFSApi(ViewContext context) {
+ HdfsApi api = null;
+ Thread.currentThread().setContextClassLoader(null);
+
+ String defaultFS = context.getProperties().get("webhdfs.url");
+ if (defaultFS == null) {
+ String message = "webhdfs.url is not configured!";
+ LOG.error(message);
+ throw new MisconfigurationFormattedException("webhdfs.url");
+ }
+
+ try {
+ api = new HdfsApi(defaultFS, getHdfsUsername(context), getHdfsAuthParams(context));
+ LOG.info("HdfsApi connected OK");
+ } catch (IOException e) {
+ String message = "HdfsApi IO error: " + e.getMessage();
+ LOG.error(message);
+ throw new ServiceFormattedException(message, e);
+ } catch (InterruptedException e) {
+ String message = "HdfsApi Interrupted error: " + e.getMessage();
+ LOG.error(message);
+ throw new ServiceFormattedException(message, e);
+ }
+ return api;
+ }
+
+ private static Map<String, String> getHdfsAuthParams(ViewContext context) {
+ String auth = context.getProperties().get("webhdfs.auth");
+ Map<String, String> params = new HashMap<String, String>();
+ if (auth == null || auth.isEmpty()) {
+ auth = "auth=SIMPLE";
+ }
+ for(String param : auth.split(";")) {
+ String[] keyvalue = param.split("=");
+ if (keyvalue.length != 2) {
+ LOG.error("Can not parse authentication param " + param + " in " + auth);
+ continue;
+ }
+ params.put(keyvalue[0], keyvalue[1]);
+ }
+ return params;
+ }
+
+ public static String getHdfsUsername(ViewContext context) {
+ String userName = context.getProperties().get("webhdfs.username");
+ if (userName == null || userName.compareTo("null") == 0 || userName.compareTo("") == 0)
+ userName = context.getUsername();
+ return userName;
+ }
+
+ public static void dropAllConnections() {
+ viewSingletonObjects.clear();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsUtil.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsUtil.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsUtil.java
new file mode 100644
index 0000000..c1c5495
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/HdfsUtil.java
@@ -0,0 +1,87 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+
+import org.apache.ambari.view.ViewContext;
+import org.apache.hadoop.fs.FSDataOutputStream;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+
+public class HdfsUtil {
+ private final static Logger LOG =
+ LoggerFactory.getLogger(HdfsUtil.class);
+
+ /**
+ * Write string to file with overwriting
+ * @param filePath path to file
+ * @param content new content of file
+ */
+ public static void putStringToFile(ViewContext context, String filePath, String content) {
+ HdfsApi hdfs = HdfsApi.getInstance(context);
+
+ FSDataOutputStream stream;
+ try {
+ stream = hdfs.create(filePath, true);
+ stream.writeBytes(content);
+ stream.close();
+ } catch (IOException e) {
+ throw new ServiceFormattedException("Could not write file " + filePath, e);
+ } catch (InterruptedException e) {
+ throw new ServiceFormattedException("Could not write file " + filePath, e);
+ }
+ }
+
+
+ /**
+ * Increment index appended to filename until find first unallocated file
+ * @param fullPathAndFilename path to file and prefix for filename
+ * @param extension file extension
+ * @return if fullPathAndFilename="/tmp/file",extension=".txt" then filename will be like "/tmp/file_42.txt"
+ */
+ public static String findUnallocatedFileName(ViewContext context, String fullPathAndFilename, String extension) {
+ HdfsApi hdfs = HdfsApi.getInstance(context);
+
+ int triesCount = 0;
+ String newFilePath;
+ boolean isUnallocatedFilenameFound;
+
+ try {
+ do {
+ newFilePath = String.format(fullPathAndFilename + "%s" + extension, (triesCount == 0) ? "" : "_" + triesCount);
+ LOG.debug("Trying to find free filename " + newFilePath);
+
+ isUnallocatedFilenameFound = !hdfs.exists(newFilePath);
+ if (isUnallocatedFilenameFound) {
+ LOG.debug("File created successfully!");
+ }
+
+ triesCount += 1;
+ } while (!isUnallocatedFilenameFound);
+ } catch (IOException e) {
+ throw new ServiceFormattedException("Error in creation: " + e.toString(), e);
+ } catch (InterruptedException e) {
+ throw new ServiceFormattedException("Error in creation: " + e.toString(), e);
+ }
+
+ return newFilePath;
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/MisconfigurationFormattedException.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/MisconfigurationFormattedException.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/MisconfigurationFormattedException.java
new file mode 100644
index 0000000..314b00b
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/MisconfigurationFormattedException.java
@@ -0,0 +1,47 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.HashMap;
+
+public class MisconfigurationFormattedException extends WebApplicationException {
+ private final static int STATUS = 500;
+ private final static String message = "Parameter \"%s\" is set to null";
+ private final static Logger LOG =
+ LoggerFactory.getLogger(MisconfigurationFormattedException.class);
+
+ public MisconfigurationFormattedException(String name) {
+ super(errorEntity(name));
+ }
+
+ protected static Response errorEntity(String name) {
+ HashMap<String, Object> response = new HashMap<String, Object>();
+ response.put("message", String.format(message, name));
+ response.put("trace", null);
+ response.put("status", STATUS);
+ return Response.status(STATUS).entity(new JSONObject(response)).type(MediaType.APPLICATION_JSON).build();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/NotFoundFormattedException.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/NotFoundFormattedException.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/NotFoundFormattedException.java
new file mode 100644
index 0000000..91b11cf
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/NotFoundFormattedException.java
@@ -0,0 +1,27 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+public class NotFoundFormattedException extends ServiceFormattedException {
+ private final static int STATUS = 404;
+
+ public NotFoundFormattedException(String message, Throwable exception) {
+ super(message, exception, STATUS);
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/ServiceFormattedException.java
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/ServiceFormattedException.java b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/ServiceFormattedException.java
new file mode 100644
index 0000000..19b324c
--- /dev/null
+++ b/contrib/views/hive/src/main/java/org/apache/ambari/view/hive/utils/ServiceFormattedException.java
@@ -0,0 +1,78 @@
+/**
+ * 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.
+ */
+
+package org.apache.ambari.view.hive.utils;
+
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.json.simple.JSONObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.security.AccessControlException;
+import java.util.HashMap;
+
+public class ServiceFormattedException extends WebApplicationException {
+ private final static Logger LOG =
+ LoggerFactory.getLogger(ServiceFormattedException.class);
+
+ public ServiceFormattedException(String message) {
+ super(errorEntity(message, null, suggestStatus(null), null));
+ }
+
+ public ServiceFormattedException(String message, Throwable exception) {
+ super(errorEntity(message, exception, suggestStatus(exception), null));
+ }
+
+ public ServiceFormattedException(String message, Throwable exception, int status) {
+ super(errorEntity(message, exception, status, null));
+ }
+
+ public ServiceFormattedException(String message, Exception ex, String curl) {
+ super(errorEntity(message, ex, suggestStatus(ex), curl));
+ }
+
+ private static int suggestStatus(Throwable exception) {
+ int status = 500;
+ if (exception == null) return status;
+ if (exception instanceof AccessControlException) {
+ status = 403;
+ }
+ return status;
+ }
+
+ protected static Response errorEntity(String message, Throwable e, int status, String header) {
+ HashMap<String, Object> response = new HashMap<String, Object>();
+ response.put("message", message);
+ String trace = null;
+ if (e != null)
+ trace = ExceptionUtils.getStackTrace(e);
+ response.put("trace", trace);
+ response.put("status", status);
+
+ if(message != null) LOG.error(message);
+ if(trace != null) LOG.debug(trace);
+
+ Response.ResponseBuilder responseBuilder = Response.status(status).entity(new JSONObject(response)).type(MediaType.APPLICATION_JSON);
+ if (header != null)
+ responseBuilder.header("X-INFO", header);
+ return responseBuilder.build();
+ }
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/resources/ui/hive-web/.gitignore
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/resources/ui/hive-web/.gitignore b/contrib/views/hive/src/main/resources/ui/hive-web/.gitignore
new file mode 100644
index 0000000..043148a
--- /dev/null
+++ b/contrib/views/hive/src/main/resources/ui/hive-web/.gitignore
@@ -0,0 +1,35 @@
+# Numerous always-ignore extensions
+*.diff
+*.err
+*.orig
+*.log
+*.rej
+*.swo
+*.swp
+*.vi
+*~
+*.sass-cache
+
+# OS or Editor folders
+.DS_Store
+.cache
+.project
+.settings
+.tmproj
+dist
+nbproject
+Thumbs.db
+
+# NPM packages folder.
+node_modules/
+
+bower_components/
+
+node/
+
+# Brunch folder for temporary files.
+tmp/
+
+public/
+
+_generators/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/resources/ui/hive-web/.jshintrc
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/resources/ui/hive-web/.jshintrc b/contrib/views/hive/src/main/resources/ui/hive-web/.jshintrc
new file mode 100644
index 0000000..c1fe863
--- /dev/null
+++ b/contrib/views/hive/src/main/resources/ui/hive-web/.jshintrc
@@ -0,0 +1,32 @@
+{
+ "predef": [
+ "document",
+ "window",
+ "-Promise"
+ ],
+ "browser" : true,
+ "boss" : true,
+ "curly": true,
+ "debug": false,
+ "devel": true,
+ "eqeqeq": false,
+ "evil": true,
+ "forin": false,
+ "immed": false,
+ "laxbreak": false,
+ "newcap": true,
+ "noarg": true,
+ "noempty": false,
+ "nonew": false,
+ "nomen": false,
+ "onevar": false,
+ "plusplus": false,
+ "regexp": false,
+ "undef": true,
+ "sub": true,
+ "strict": false,
+ "white": false,
+ "eqnull": true,
+ "esnext": true,
+ "unused": true
+}
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/resources/ui/hive-web/Brocfile.js
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/resources/ui/hive-web/Brocfile.js b/contrib/views/hive/src/main/resources/ui/hive-web/Brocfile.js
new file mode 100644
index 0000000..db65f1f
--- /dev/null
+++ b/contrib/views/hive/src/main/resources/ui/hive-web/Brocfile.js
@@ -0,0 +1,46 @@
+/**
+ * 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.
+ */
+
+/* global require, module */
+
+var EmberApp = require('ember-cli/lib/broccoli/ember-app');
+
+var app = new EmberApp({
+ 'ember-cli-selectize': {
+ //valid values are `default`, `bootstrap2`, `bootstrap3` or false
+ 'theme': 'bootstrap3'
+ },
+ hinting: false
+});
+
+app.import('bower_components/bootstrap/dist/js/bootstrap.js');
+app.import('bower_components/bootstrap/dist/css/bootstrap.css');
+app.import('bower_components/bootstrap/dist/css/bootstrap.css.map', {
+ destDir: 'assets'
+});
+
+app.import('bower_components/ember-i18n/lib/i18n.js');
+app.import('bower_components/ember-i18n/lib/i18n-plurals.js');
+
+app.import('vendor/codemirror/codemirror-min.js');
+app.import('vendor/codemirror/sql-hint.js');
+app.import('vendor/codemirror/show-hint.js');
+app.import('vendor/codemirror/codemirror.css');
+app.import('vendor/codemirror/show-hint.css');
+
+module.exports = app.toTree();
http://git-wip-us.apache.org/repos/asf/ambari/blob/f5482d89/contrib/views/hive/src/main/resources/ui/hive-web/README.md
----------------------------------------------------------------------
diff --git a/contrib/views/hive/src/main/resources/ui/hive-web/README.md b/contrib/views/hive/src/main/resources/ui/hive-web/README.md
new file mode 100644
index 0000000..2237863
--- /dev/null
+++ b/contrib/views/hive/src/main/resources/ui/hive-web/README.md
@@ -0,0 +1,14 @@
+<!---
+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](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.
+-->