Search in sources :

Example 6 with OperationException

use of jetbrains.buildServer.server.rest.errors.OperationException in project teamcity-rest by JetBrains.

the class PropEntityTrigger method addToInternalMain.

@NotNull
public BuildTriggerDescriptor addToInternalMain(@NotNull final BuildTypeSettingsEx buildType, @NotNull final ServiceLocator serviceLocator) {
    if (StringUtil.isEmpty(type)) {
        throw new BadRequestException("Build trigger cannot have empty 'type'.");
    }
    BuildTriggerDescriptor similar = getInheritedOrSameIdSimilar(buildType, serviceLocator);
    if (inherited != null && inherited && similar != null) {
        return similar;
    }
    if (similar != null && id != null && id.equals(similar.getId())) {
        // todo
        return similar;
    }
    final BuildTriggerDescriptor triggerToAdd = serviceLocator.getSingletonService(BuildTriggerDescriptorFactory.class).createTriggerDescriptor(type, properties == null ? Collections.emptyMap() : properties.getMap(), buildTriggerCustomization == null ? BuildCustomizationSettings.empty() : buildTriggerCustomization.toBuildCustomizationSettings(serviceLocator));
    if (!buildType.addBuildTrigger(triggerToAdd)) {
        String additionalMessage = getDetails(buildType, triggerToAdd);
        throw new OperationException("Build trigger addition failed." + (additionalMessage != null ? " " + additionalMessage : ""));
    }
    if (disabled != null) {
        buildType.setEnabled(triggerToAdd.getId(), !disabled);
    }
    BuildTriggerDescriptor result = buildType.findTriggerById(triggerToAdd.getId());
    if (result == null) {
        throw new OperationException("Cannot find just added trigger with id '" + triggerToAdd.getId() + "'");
    }
    return result;
}
Also used : BuildTriggerDescriptor(jetbrains.buildServer.buildTriggers.BuildTriggerDescriptor) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) BuildTriggerDescriptorFactory(jetbrains.buildServer.buildTriggers.BuildTriggerDescriptorFactory) OperationException(jetbrains.buildServer.server.rest.errors.OperationException) NotNull(org.jetbrains.annotations.NotNull)

Example 7 with OperationException

use of jetbrains.buildServer.server.rest.errors.OperationException in project teamcity-rest by JetBrains.

the class Sessions method getSessions.

@NotNull
private Collection<Session> getSessions(@NotNull final MBeanServer serverBean, @NotNull final ObjectName managerBean, @NotNull final Fields fields, @NotNull final BeanContext beanContext) {
    String sessionsListRaw;
    try {
        sessionsListRaw = String.valueOf(serverBean.invoke(managerBean, "listSessionIds", null, null));
    } catch (Exception e) {
        throw new OperationException("Could not get sessions data: " + e.toString(), e);
    }
    final String[] sessionIds = sessionsListRaw.split(" ");
    final ArrayList<Session> result = new ArrayList<Session>(sessionIds.length);
    for (String sessionId : sessionIds) {
        Long userId;
        try {
            userId = getSessionUserId(serverBean, managerBean, sessionId);
        } catch (Exception e) {
            userId = null;
            LOG.debug("Cannot retrieve userId for session with id '" + sessionId + "': " + e.toString());
        }
        Long creationTimestamp = (Long) getBeanOperationResult(serverBean, managerBean, sessionId, "getCreationTimestamp");
        Long lastAccessedTimestamp = (Long) getBeanOperationResult(serverBean, managerBean, sessionId, "getLastAccessedTimestamp");
        result.add(new Session(sessionId, userId, creationTimestamp == null ? null : new Date(creationTimestamp), lastAccessedTimestamp == null ? null : new Date(lastAccessedTimestamp), fields, beanContext));
    }
    return SESSION_ORDERING.sortedCopy(result);
}
Also used : ArrayList(java.util.ArrayList) OperationException(jetbrains.buildServer.server.rest.errors.OperationException) OperationException(jetbrains.buildServer.server.rest.errors.OperationException) Date(java.util.Date) NotNull(org.jetbrains.annotations.NotNull)

Example 8 with OperationException

use of jetbrains.buildServer.server.rest.errors.OperationException in project teamcity-rest by JetBrains.

the class FilesSubResource method processCoreDownload.

private void processCoreDownload(@NotNull final Element element, @NotNull final HttpServletRequest request, @NotNull final HttpServletResponse response) {
    setCacheControl(request, response);
    boolean setContentDisposition = getSetContentDisposition(element, request, response);
    try {
        myBeanContext.getSingletonService(HttpDownloadProcessor.class).processDownload(new HttpDownloadProcessor.FileInfo() {

            @Override
            public long getLastModified() {
                return FilesSubResource.getLastModified(element);
            }

            @Override
            public long getFileSize() {
                return element.getSize();
            }

            @Override
            @NotNull
            public String getFileName() {
                return element.getName();
            }

            @Override
            @NotNull
            public String getFileDigest() {
                // note: "aggregated" build artifacts are still not handled in due way here
                return getETag(element, myUrlPrefix);
            }

            @Override
            @NotNull
            public InputStream getInputStream() throws IOException {
                // todo: see this method in HttpDownloadProcessor
                return element.getInputStream();
            }
        }, setContentDisposition, /*header is forced to attachment above*/
        request, response);
    } catch (IOException e) {
        // todo add better processing
        throw new OperationException("Error while processing file '" + element.getFullName() + "': " + e.toString(), e);
    }
}
Also used : HttpDownloadProcessor(jetbrains.buildServer.controllers.HttpDownloadProcessor) InputStream(java.io.InputStream) IOException(java.io.IOException) NotNull(org.jetbrains.annotations.NotNull) OperationException(jetbrains.buildServer.server.rest.errors.OperationException)

Example 9 with OperationException

use of jetbrains.buildServer.server.rest.errors.OperationException in project teamcity-rest by JetBrains.

the class DebugRequest method saveMemoryDump.

/**
 * Experimental use only!
 */
@POST
@Path("/memory/dumps")
@Produces({ "text/plain" })
public String saveMemoryDump(@QueryParam("archived") Boolean archived, @Context HttpServletRequest request) {
    myDataProvider.checkGlobalPermission(Permission.MANAGE_SERVER_INSTALLATION);
    final File logsPath = myDataProvider.getBean(ServerPaths.class).getLogsPath();
    try {
        final File memoryDumpFile = DiagnosticUtil.memoryDump(new File(logsPath, "memoryDumps"), archived == null || archived, "via REST API by user " + LogUtil.describe(SessionUser.getUser(request)), Loggers.SERVER);
        return memoryDumpFile.getAbsolutePath();
    } catch (Exception e) {
        throw new OperationException("Error saving memory dump", e);
    }
}
Also used : File(java.io.File) BadRequestException(jetbrains.buildServer.server.rest.errors.BadRequestException) OperationException(jetbrains.buildServer.server.rest.errors.OperationException) NotFoundException(jetbrains.buildServer.server.rest.errors.NotFoundException) AuthorizationFailedException(jetbrains.buildServer.server.rest.errors.AuthorizationFailedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) OperationException(jetbrains.buildServer.server.rest.errors.OperationException)

Example 10 with OperationException

use of jetbrains.buildServer.server.rest.errors.OperationException in project teamcity-rest by JetBrains.

the class DebugRequest method getRequestDetails.

/**
 * Experimental use only!
 */
@GET
// "extra" here is to allow checking arbitrary chars in the URL path
@Path("/currentRequest/details" + "{extra:(/.*)?}")
@Produces({ "text/plain" })
public String getRequestDetails(@PathParam("extra") final String extra, @Context HttpServletRequest request) {
    if (!TeamCityProperties.getBoolean("rest.debug.currentRequest.details.allowUnauthorized")) {
        myDataProvider.checkGlobalPermission(Permission.MANAGE_SERVER_INSTALLATION);
    }
    StringBuilder result = new StringBuilder();
    String remoteAddress = WebUtil.hostAndPort(request.getRemoteAddr(), request.getRemotePort());
    result.append("Client address: ").append(remoteAddress);
    String refinedRemoteAddress = WebUtil.hostAndPort(WebUtil.getRemoteAddress(request), request.getRemotePort());
    if (!refinedRemoteAddress.equals(remoteAddress))
        result.append(" (").append(refinedRemoteAddress).append(")");
    result.append("\n");
    result.append("Local address: ").append(WebUtil.hostAndPort(request.getLocalAddr(), request.getLocalPort())).append("\n");
    if (request.getLocalPort() != request.getServerPort()) {
        result.append("Server port: ").append(request.getServerPort()).append("\n");
    }
    result.append("Method: ").append(request.getMethod()).append("\n");
    result.append("Scheme: ").append(request.getScheme()).append("\n");
    result.append("Path and query: ").append(WebUtil.getRequestUrl(request)).append("\n");
    if (!StringUtil.isEmpty(extra))
        result.append("Extra path: ").append(extra).append("\n");
    result.append("Session id: ").append(request.getSession().getId()).append("\n");
    result.append("Request object instance hash: ").append(Integer.toHexString(request.hashCode())).append("\n");
    result.append("Current TeamCity user: ").append(myServiceLocator.getSingletonService(PermissionChecker.class).getCurrentUserDescription()).append("\n");
    result.append("\n");
    result.append("Headers:\n");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerName = headerNames.nextElement();
        Enumeration<String> headers = request.getHeaders(headerName);
        while (headers.hasMoreElements()) {
            String header = headers.nextElement();
            result.append(headerName).append(": ").append(header).append("\n");
        }
    }
    result.append("\n");
    try {
        // consider using byte-to-byte copy method
        StringUtil.processLines(request.getInputStream(), new StringUtil.LineProcessor() {

            @Override
            public boolean processLine(final String line) {
                result.append(line);
                return true;
            }
        });
    } catch (IOException e) {
        throw new OperationException("Error reading request body: " + e.getMessage(), e);
    }
    return result.toString();
}
Also used : IOException(java.io.IOException) OperationException(jetbrains.buildServer.server.rest.errors.OperationException)

Aggregations

OperationException (jetbrains.buildServer.server.rest.errors.OperationException)14 NotNull (org.jetbrains.annotations.NotNull)9 IOException (java.io.IOException)7 BadRequestException (jetbrains.buildServer.server.rest.errors.BadRequestException)7 NotFoundException (jetbrains.buildServer.server.rest.errors.NotFoundException)5 InputStream (java.io.InputStream)2 UnknownHostException (java.net.UnknownHostException)2 SQLException (java.sql.SQLException)2 ArrayList (java.util.ArrayList)2 Collectors (java.util.stream.Collectors)2 XmlAttribute (javax.xml.bind.annotation.XmlAttribute)2 XmlElement (javax.xml.bind.annotation.XmlElement)2 XmlRootElement (javax.xml.bind.annotation.XmlRootElement)2 XmlType (javax.xml.bind.annotation.XmlType)2 ServiceLocator (jetbrains.buildServer.ServiceLocator)2 AuthorizationFailedException (jetbrains.buildServer.server.rest.errors.AuthorizationFailedException)2 SUser (jetbrains.buildServer.users.SUser)2 Stopwatch (com.google.common.base.Stopwatch)1 Logger (com.intellij.openapi.diagnostic.Logger)1 StringUtil (com.intellij.openapi.util.text.StringUtil)1