Example usage for java.lang SecurityException SecurityException

List of usage examples for java.lang SecurityException SecurityException

Introduction

In this page you can find the example usage for java.lang SecurityException SecurityException.

Prototype

public SecurityException(Throwable cause) 

Source Link

Document

Creates a SecurityException with the specified cause and a detail message of (cause==null ?

Usage

From source file:org.openanzo.activemq.internal.SecurityBroker.java

@Override
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
    //   resetlock.readLock().lock();
    //   try {/*from  w w w. j  a va 2 s.co  m*/
    final ServerSecurityContext subject = (ServerSecurityContext) context.getSecurityContext();
    if (subject == null) {
        MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
        String errorMsg = "Connection is not authenticated:" + context.getClientId();
        log.error(LogUtils.SECURITY_MARKER, errorMsg);
        MDC.clear();
        throw new SecurityException(errorMsg);
    }
    if (!subject.getAuthorizedReadDests().containsKey(info.getDestination())) {
        if (info.getDestination().getPhysicalName().startsWith("services/")) {
            if (!subject.getAnzoPrincipal().isSysadmin()) {
                MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                String errorMsg = Messages.formatString(
                        ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(),
                        "read", info.getDestination().toString());
                log.info(LogUtils.SECURITY_MARKER, errorMsg);
                MDC.clear();
                throw new SecurityException(errorMsg);
            }
        } else if (info.getDestination().isTemporary() && !((ActiveMQTempDestination) info.getDestination())
                .getConnectionId().equals(context.getConnectionId().getValue())) {
            MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
            MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
            String errorMsg = Messages.formatString(
                    ExceptionConstants.COMBUS.ERROR_CONNECTION_NOT_AUTHENTICATED, subject.getUserName(), "read",
                    info.getDestination().toString());
            log.info(LogUtils.SECURITY_MARKER, errorMsg);
            MDC.clear();
            throw new SecurityException(errorMsg);
        } else {
            IOperationContext opContext = null;
            try {
                String destinationName = info.getDestination().getPhysicalName();
                if (destinationName.startsWith(NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX)
                        || destinationName.startsWith(NAMESPACES.STREAM_TOPIC_PREFIX)) {
                    opContext = new BaseOperationContext(ADD_CONSUMER, context.getConnectionId().toString(),
                            principal);
                    opContext.setMDC();
                    if (!subject.getAnzoPrincipal().isSysadmin()) {
                        if (primaryDatasource == null) {
                            MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                            MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                            String logMsg = Messages
                                    .formatString(ExceptionConstants.COMBUS.ERROR_SERVER_NOT_READY);
                            log.warn(LogUtils.COMBUS_MARKER, logMsg);
                            MDC.clear();
                            throw new SecurityException(logMsg);
                        }
                        String namedGraphUUIDUri = null;
                        if (destinationName.startsWith(NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX)) {
                            namedGraphUUIDUri = UriGenerator.stripEncapsulatedString(
                                    NAMESPACES.NAMEDGRAPH_TOPIC_PREFIX, destinationName);
                        } else {
                            namedGraphUUIDUri = UriGenerator
                                    .stripEncapsulatedString(NAMESPACES.STREAM_TOPIC_PREFIX, destinationName);
                        }
                        URI namedGraphUri = null;
                        try {
                            namedGraphUri = primaryDatasource.getModelService().getUriForUUID(opContext,
                                    Constants.valueFactory.createURI(namedGraphUUIDUri));
                        } catch (AnzoException e) {
                            String logMsg = Messages.formatString(
                                    ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID,
                                    namedGraphUUIDUri);
                            log.debug(LogUtils.DATASOURCE_MARKER, logMsg, e);
                            throw new SecurityException(logMsg, e);
                        }
                        if (namedGraphUri == null) {
                            String logMsg = Messages.formatString(
                                    ExceptionConstants.DATASOURCE.NAMEDGRAPH.GRAPH_NOT_VALID,
                                    namedGraphUUIDUri);
                            log.debug(LogUtils.DATASOURCE_MARKER, logMsg);
                            throw new SecurityException(logMsg);
                        }
                        Set<URI> roles = primaryDatasource.getAuthorizationService().getRolesForGraph(opContext,
                                namedGraphUri, Privilege.READ);
                        if (!org.openanzo.rdf.utils.Collections.memberOf(roles,
                                subject.getAnzoPrincipal().getRoles())) {
                            MDC.put(LogUtils.REMOTE_ADDRESS, context.getConnection().getRemoteAddress());
                            MDC.put(LogUtils.USER, subject.getAnzoPrincipal().getName());
                            String errorMsg = Messages.formatString(
                                    ExceptionConstants.COMBUS.NOT_AUTHORIZED_FOR_TOPIC, subject.getUserName(),
                                    "read", info.getDestination().toString());
                            log.info(LogUtils.SECURITY_MARKER, errorMsg);
                            MDC.clear();
                            throw new SecurityException(errorMsg);
                        }
                    }
                }
            } finally {
                if (opContext != null) {
                    opContext.clearMDC();
                }
            }
        }
        subject.getAuthorizedReadDests().put(info.getDestination(), info.getDestination());
    }
    return super.addConsumer(context, info);
}

From source file:org.betaconceptframework.astroboa.console.jsf.login.LoginBean.java

@Observer(Identity.EVENT_PRE_AUTHENTICATE)
public void configSeamPrincipal() {

    SecurityContext securityContext = AstroboaClientContextHolder.getActiveSecurityContext();

    //Expect to find a principal of Type IdentityPrincipal
    //inside Subject's Principals
    if (securityContext == null || securityContext.getSubject() == null
            || CollectionUtils.isEmpty(securityContext.getSubject().getPrincipals(IdentityPrincipal.class))) {
        throw new SecurityException("Identity Principal is missing");
    } else {/*from  www .  j  a va2 s. c  o  m*/
        Identity.instance().acceptExternallyAuthenticatedPrincipal(new IdentityPrincipal(securityContext
                .getSubject().getPrincipals(IdentityPrincipal.class).iterator().next().getName()));

    }
}

From source file:org.apache.bookkeeper.tls.TLSContextFactory.java

@Override
public synchronized void init(NodeType type, AbstractConfiguration conf, ByteBufAllocator allocator)
        throws SecurityException {
    this.allocator = allocator;
    final String enabledProtocols;
    final String enabledCiphers;

    enabledCiphers = conf.getTLSEnabledCipherSuites();
    enabledProtocols = conf.getTLSEnabledProtocols();

    try {//from   w w  w.  j a  va2 s .  c  o m
        switch (type) {
        case Client:
            createClientContext(conf);
            break;
        case Server:
            createServerContext(conf);
            break;
        default:
            throw new SecurityException(new IllegalArgumentException("Invalid NodeType"));
        }

        if (enabledProtocols != null && !enabledProtocols.isEmpty()) {
            protocols = enabledProtocols.split(",");
        }

        if (enabledCiphers != null && !enabledCiphers.isEmpty()) {
            ciphers = enabledCiphers.split(",");
        }
    } catch (KeyStoreException e) {
        throw new RuntimeException("Standard keystore type missing", e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Standard algorithm missing", e);
    } catch (CertificateException e) {
        throw new SecurityException("Unable to load keystore", e);
    } catch (IOException e) {
        throw new SecurityException("Error initializing SSLContext", e);
    } catch (UnrecoverableKeyException e) {
        throw new SecurityException("Unable to load key manager, possibly bad password", e);
    } catch (InvalidKeySpecException e) {
        throw new SecurityException("Unable to load key manager", e);
    } catch (IllegalArgumentException e) {
        throw new SecurityException("Invalid TLS configuration", e);
    } catch (NoSuchProviderException e) {
        throw new SecurityException("No such provider", e);
    }
}

From source file:org.onecmdb.core.utils.wsdl.OneCMDBWebServiceImpl.java

public int evalRelationCount(String auth, CiBean source, String relationPath, QueryCriteria crit) {
    long start = System.currentTimeMillis();
    log.info("WSDL: evalRelationCount(" + auth + ", " + relationPath + ")");

    // Update all beans.
    ISession session = onecmdb.getSession(auth);
    if (session == null) {
        throw new SecurityException("No Session found! Try to do auth() first!");
    }/*from   www.ja  v  a  2 s.  c  o  m*/

    if (source == null) {
        throw new IllegalArgumentException("Source can not be null!");
    }

    ICi ci = getICI(session, source);

    // Lookup the source
    OnecmdbUtils utils = new OnecmdbUtils(session);
    //Set<IValue> set = utils.evaluate(ci, relationPath);
    QueryResult result = utils.evaluate(ci, relationPath, crit, true);

    // Convert Values to Beans.
    long stop = System.currentTimeMillis();
    log.info("WSDL: evalRelationCount completed in " + (stop - start) + "ms returned + " + result.size()
            + " objects");
    return (result.getTotalHits());
}

From source file:it.greenvulcano.gvesb.iam.service.internal.GVUsersManager.java

@Override
public void addRole(String username, String rolename) {
    if (!rolename.matches(Role.ROLE_PATTERN))
        throwException(new InvalidRoleException(rolename));

    User user = userRepository.get(username)
            .orElseThrow(() -> new SecurityException(new UserNotFoundException(username)));

    Role role = roleRepository.get(rolename).orElse(new RoleJPA(rolename, "Created by JAAS"));
    user.addRole(role);//from w  w w. j  a v  a 2s .co  m

    userRepository.add(user);

}

From source file:org.nuxeo.ecm.platform.semanticentities.service.LocalEntityServiceImpl.java

@Override
public OccurrenceRelation addOccurrences(CoreSession session, DocumentRef docRef, DocumentRef entityRef,
        List<OccurrenceInfo> occurrences) throws ClientException {
    if (!session.hasPermission(docRef, Constants.ADD_OCCURRENCE_PERMISSION)) {
        // check the permission on the source document
        throw new SecurityException(String.format(
                "%s has not the permission to add an entity" + " occurrence on document with id '%s'",
                session.getPrincipal().getName(), docRef));
    }/*  w  ww  .j  a  v  a  2  s  . c o  m*/
    OccurrenceRelation relation = getOccurrenceRelation(session, docRef, entityRef, true);
    if (occurrences != null && !occurrences.isEmpty()) {
        relation.addOccurrences(occurrences);
    }
    UpdateOrCreateOccurrenceRelation op = new UpdateOrCreateOccurrenceRelation(session, relation, this);
    op.runUnrestricted();
    return session.getDocument(op.occRef).getAdapter(OccurrenceRelation.class, true);
}

From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java

@Override
public MetadataResource patchResourceStatus(ServiceContext context, String metadataUuid, String resourceId,
        MetadataResourceVisibility visibility) throws Exception {
    ApplicationContext _appContext = ApplicationContextHolder.get();
    AccessManager accessManager = _appContext.getBean(AccessManager.class);
    String metadataId = getAndCheckMetadataId(metadataUuid);

    if (accessManager.canEdit(context, metadataId)) {
        Path filePath = getResource(context, metadataUuid, resourceId);

        GeonetworkDataDirectory dataDirectory = _appContext.getBean(GeonetworkDataDirectory.class);
        Path metadataDir = Lib.resource.getMetadataDir(dataDirectory, metadataId);
        Path newFolderPath = metadataDir.resolve(visibility.toString());
        if (!Files.exists(newFolderPath)) {
            try {
                Files.createDirectories(newFolderPath);
            } catch (Exception e) {
                throw new IOException(String.format(
                        "Can't create folder '%s' to store resource with name '%s' for metadata '%s'.",
                        visibility, resourceId, metadataUuid));
            }/*  w w w.  j  a  va2  s . co m*/
        }
        Path newFilePath = newFolderPath.resolve(filePath.getFileName());
        Files.move(filePath, newFilePath);
        return getResourceDescription(metadataUuid, visibility, newFilePath);
    } else {
        throw new SecurityException(String.format(
                "Current user can't edit metadata '%s' and as such can't change the resource status for '%s'.",
                metadataUuid, resourceId));
    }
}

From source file:be.agiv.security.AGIVSecurity.java

/**
 * Enable the AGIV security on the given JAX-WS binding provider. Each
 * JAX-WS port can be casted to a JAX-WS binding provider.
 * <p/>/*from   w  ww  .  j ava  2s  .co  m*/
 * It is no problem to call the enable method multiple times for a certain
 * JAX-WS stub. This method will only decorate the AGIV Security framework
 * once on the given JAX-WS stub. If the JAX-WS stub is already decorated by
 * another AGIVSecurity instance a {@link SecurityException} will be thrown.
 * 
 * @param bindingProvider
 *            the JAX-WS binding provider on which to enable the AGIV
 *            security framework.
 * @param useWsSecureConversation
 *            set to <code>true</code> if WS-SecureConversation should be
 *            used.
 * @param serviceRealm
 *            the optional service realm.
 * @see AGIVSecurity#enable(BindingProvider, String)
 * @see AGIVSecurity#enable(BindingProvider, String, boolean)
 * @see AGIVSecurity#disable(BindingProvider)
 */
public void enable(BindingProvider bindingProvider, boolean useWsSecureConversation, String serviceRealm) {
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    for (Handler handler : handlerChain) {
        if (handler instanceof SecureConversationHandler || handler instanceof AuthenticationHandler) {
            LOG.warn("security already enabled");
            SecurityTokenConsumer securityTokenConsumer = (SecurityTokenConsumer) handler;
            if (this != securityTokenConsumer.getSecurityTokenProvider()) {
                throw new SecurityException(
                        "security on JAX-WS stub already enabled by another AGIVSecurity instance");
            }
            return;
        }
    }
    WSSecurityHandler wsSecurityHandler = new WSSecurityHandler();
    if (useWsSecureConversation) {
        handlerChain.add(new SecureConversationHandler(this, wsSecurityHandler, serviceRealm));
    } else {
        handlerChain.add(new AuthenticationHandler(this, wsSecurityHandler, serviceRealm));
    }
    handlerChain.add(wsSecurityHandler);
    handlerChain.add(new LoggingHandler());
    binding.setHandlerChain(handlerChain);
}

From source file:org.apereo.portal.portlets.portletadmin.PortletAdministrationHelper.java

/**
 * Persist a new or edited PortletDefinition from a form, replacing existing values.
 *
 * @param publisher     {@code IPerson} that requires permission to save this definition
 * @param form          form data to persist
 * @return              new {@code PortletDefinitionForm} for this portlet ID
 *//*  w  w w.ja v  a  2 s.  c  om*/
public PortletDefinitionForm savePortletRegistration(IPerson publisher, PortletDefinitionForm form)
        throws Exception {

    /* TODO:  Service-Layer Security Reboot (great need of refactoring with a community-approved plan in place) */

    // User must have the selected lifecycle permission over AT LEAST ONE
    // category in which this portlet resides.  (This is the same check that
    // is made when the user enters the lifecycle-selection step in the wizard.)
    if (!hasLifecyclePermission(publisher, form.getLifecycleState(), form.getCategories())) {
        logger.warn("User '" + publisher.getUserName()
                + "' attempted to save the following portlet without the selected MANAGE permission:  " + form);
        throw new SecurityException("Not Authorized");
    }

    if (!form.isNew()) {
        // User must have the previous lifecycle permission
        // in AT LEAST ONE previous category as well
        IPortletDefinition def = this.portletDefinitionRegistry.getPortletDefinition(form.getId());
        Set<PortletCategory> categories = portletCategoryRegistry.getParentCategories(def);
        SortedSet<JsonEntityBean> categoryBeans = new TreeSet<>();
        for (PortletCategory cat : categories) {
            categoryBeans.add(new JsonEntityBean(cat));
        }
        if (!hasLifecyclePermission(publisher, def.getLifecycleState(), categoryBeans)) {
            logger.warn("User '" + publisher.getUserName()
                    + "' attempted to save the following portlet without the previous MANAGE permission:  "
                    + form);
            throw new SecurityException("Not Authorized");
        }
    }

    if (form.isNew() || portletDefinitionRegistry.getPortletDefinition(form.getId()).getType().getId() != form
            .getTypeId()) {
        // User must have access to the selected CPD if s/he selected it in this interaction
        final int selectedTypeId = form.getTypeId();
        final PortletPublishingDefinition cpd = portletPublishingDefinitionDao
                .getChannelPublishingDefinition(selectedTypeId);
        final Map<IPortletType, PortletPublishingDefinition> allowableCpds = this
                .getAllowableChannelPublishingDefinitions(publisher);
        if (!allowableCpds.containsValue(cpd)) {
            logger.warn("User '" + publisher.getUserName()
                    + "' attempted to administer the following portlet without the selected "
                    + IPermission.PORTLET_MANAGER_SELECT_PORTLET_TYPE + " permission:  " + form);
            throw new SecurityException("Not Authorized");
        }
    }

    // create the principal array from the form's principal list -- only principals with permissions
    final Set<IGroupMember> subscribePrincipalSet = new HashSet<>(form.getPrincipals().size());
    final Set<IGroupMember> browsePrincipalSet = new HashSet<>(form.getPrincipals().size());
    for (JsonEntityBean bean : form.getPrincipals()) {
        final String subscribePerm = bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_SUBSCRIBER_ACTIVITY;
        final String browsePerm = bean.getTypeAndIdHash() + "_" + IPermission.PORTLET_BROWSE_ACTIVITY;
        final EntityEnum entityEnum = bean.getEntityType();
        final IGroupMember principal = entityEnum.isGroup() ? (GroupService.findGroup(bean.getId()))
                : (GroupService.getGroupMember(bean.getId(), entityEnum.getClazz()));
        if (form.getPermissions().contains(subscribePerm)) {
            subscribePrincipalSet.add(principal);
        }
        if (form.getPermissions().contains(browsePerm)) {
            browsePrincipalSet.add(principal);
        }
    }

    // create the category list from the form's category bean list
    List<PortletCategory> categories = new ArrayList<>();
    for (JsonEntityBean category : form.getCategories()) {
        String id = category.getId();
        String iCatID = id.startsWith("cat") ? id.substring(3) : id;
        categories.add(portletCategoryRegistry.getPortletCategory(iCatID));
    }

    final IPortletType portletType = portletTypeRegistry.getPortletType(form.getTypeId());
    if (portletType == null) {
        throw new IllegalArgumentException("No IPortletType exists for ID " + form.getTypeId());
    }

    IPortletDefinition portletDef;
    if (form.getId() == null) {
        portletDef = new PortletDefinitionImpl(portletType, form.getFname(), form.getName(), form.getTitle(),
                form.getApplicationId(), form.getPortletName(), form.isFramework());
    } else {
        portletDef = portletDefinitionRegistry.getPortletDefinition(form.getId());
        portletDef.setType(portletType);
        portletDef.setFName(form.getFname());
        portletDef.setName(form.getName());
        portletDef.setTitle(form.getTitle());
        portletDef.getPortletDescriptorKey().setWebAppName(form.getApplicationId());
        portletDef.getPortletDescriptorKey().setPortletName(form.getPortletName());
        portletDef.getPortletDescriptorKey().setFrameworkPortlet(form.isFramework());
    }
    portletDef.setDescription(form.getDescription());
    portletDef.setTimeout(form.getTimeout());

    // Make parameters (NB:  these are different from preferences) in the
    // portletDef reflect the state of the form, in case any have changed.
    for (String key : form.getParameters().keySet()) {
        String value = form.getParameters().get(key).getValue();
        if (!StringUtils.isBlank(value)) {
            portletDef.addParameter(key, value);
        }
    }
    portletDef.addParameter(IPortletDefinition.EDITABLE_PARAM, Boolean.toString(form.isEditable()));
    portletDef.addParameter(IPortletDefinition.CONFIGURABLE_PARAM, Boolean.toString(form.isConfigurable()));
    portletDef.addParameter(IPortletDefinition.HAS_HELP_PARAM, Boolean.toString(form.isHasHelp()));
    portletDef.addParameter(IPortletDefinition.HAS_ABOUT_PARAM, Boolean.toString(form.isHasAbout()));

    // Now add portlet preferences
    List<IPortletPreference> preferenceList = new ArrayList<>();
    for (String key : form.getPortletPreferences().keySet()) {
        List<String> prefValues = form.getPortletPreferences().get(key).getValue();
        if (prefValues != null && prefValues.size() > 0) {
            String[] values = prefValues.toArray(new String[prefValues.size()]);
            BooleanAttribute readOnly = form.getPortletPreferenceReadOnly().get(key);
            preferenceList.add(new PortletPreferenceImpl(key, readOnly.getValue(), values));
        }
    }
    portletDef.setPortletPreferences(preferenceList);

    // Lastly update the PortletDefinition's lifecycle state & lifecycle-related metadata
    updateLifecycleState(form, portletDef, publisher);

    // The final parameter of IGroupMembers is used to set the initial SUBSCRIBE permission set
    portletPublishingService.savePortletDefinition(portletDef, publisher, categories,
            new ArrayList<>(subscribePrincipalSet));
    //updatePermissions(portletDef, subscribePrincipalSet, IPermission.PORTLET_SUBSCRIBER_ACTIVITY);
    updatePermissions(portletDef, browsePrincipalSet, IPermission.PORTLET_BROWSE_ACTIVITY);

    return this.createPortletDefinitionForm(publisher, portletDef.getPortletDefinitionId().getStringId());
}

From source file:org.kawanfw.sql.servlet.sql.ServerStatementRawExecute.java

/**
 * Execute the passed SQL Statement as execute(sql) and return: <br>
 * - The result set as a List of Maps for SELECT statements. <br>
 * - The return code for other statements
 * /*from w w  w . j ava  2s  . c o  m*/
 * @param sqlOrder
 *            the qsql order
 * @param sqlParms
 *            the sql parameters
 * @param out
 *            the output stream where to write to result set output
 * 
 * 
 * @throws SQLException
 */
private void executeStatement(OutputStream out) throws SQLException, IOException {

    String sqlOrder = statementHolder.getSqlOrder();

    // sqlOrder = HtmlConverter.fromHtml(sqlOrder);

    // Should never be called?
    if (statementHolder.isDoExtractResultSetMetaData()) {
        sqlOrder = DbVendorManager.addLimit1(sqlOrder, connection);
    }

    Statement statement = null;

    try {

        if (!SqlConfiguratorCall.allowExecute(sqlConfigurator, username, connection)) {
            String ipAddress = request.getRemoteAddr();

            SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                    sqlOrder, new Vector<Object>());

            String message = Tag.PRODUCT_SECURITY + " [" + "{Statement not authorized for execute}"
                    + "{sql order : " + sqlOrder + "}" + "]";

            throw new SecurityException(message);
        }

        statement = connection.createStatement();
        ServerSqlUtil.setStatementProperties(statement, statementHolder);

        debug("before ServerPreparedStatementParameters");

        boolean isAllowed = sqlConfigurator.allowStatementAfterAnalysis(username, connection, sqlOrder,
                new Vector<Object>());

        if (!isAllowed) {

            String ipAddress = request.getRemoteAddr();

            SqlConfiguratorCall.runIfStatementRefused(sqlConfigurator, username, connection, ipAddress,
                    sqlOrder, new Vector<Object>());

            String message = Tag.PRODUCT_SECURITY + " [" + "{Statement not authorized}" + "{sql order: "
                    + sqlOrder + "}]";

            throw new SecurityException(message);
        }

        debug("before statement.execute(sqlOrder)");
        debug("sqlOrder: " + sqlOrder);

        ServerSqlUtil.setMaxRowsToReturn(statement, sqlConfigurator);

        boolean isResultSet = false;

        boolean usesAutoGeneratedKeys = false;

        if (statementHolder.getAutoGeneratedKeys() != -1) {
            isResultSet = statement.execute(sqlOrder, statementHolder.getAutoGeneratedKeys());
            usesAutoGeneratedKeys = true;
        } else if (statementHolder.getColumnIndexesAutogenerateKeys().length != 0) {
            isResultSet = statement.execute(sqlOrder, statementHolder.getColumnIndexesAutogenerateKeys());
            usesAutoGeneratedKeys = true;
        } else if (statementHolder.getColumnNamesAutogenerateKeys().length != 0) {
            isResultSet = statement.execute(sqlOrder, statementHolder.getColumnNamesAutogenerateKeys());
            usesAutoGeneratedKeys = true;
        } else {
            debug("before isResultSet = statement.execute(sqlOrder);");
            isResultSet = statement.execute(sqlOrder);
        }

        debug("isResultSet          :" + isResultSet);
        debug("usesAutoGeneratedKeys: " + usesAutoGeneratedKeys);

        if (isResultSet) {
            ResultSet rs = statement.getResultSet();

            try {

                //br.write(TransferStatus.SEND_OK + CR_LF);
                ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);

                ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator,
                        fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder);

                resultSetWriter.write(rs);
            } finally {
                if (rs != null)
                    rs.close();
            }
        } else {

            debug("int rc = statement.getUpdateCount();");
            int rc = statement.getUpdateCount();

            //br.write(TransferStatus.SEND_OK + CR_LF);
            //br.write("getUpdateCount=" + rc + CR_LF);
            ServerSqlManager.writeLine(out, TransferStatus.SEND_OK);
            ServerSqlManager.writeLine(out, "getUpdateCount=" + rc);

            if (usesAutoGeneratedKeys) {
                ResultSet rs = statement.getGeneratedKeys();

                try {
                    ResultSetWriter resultSetWriter = new ResultSetWriter(request, out, commonsConfigurator,
                            fileConfigurator, sqlConfigurator, username, sqlOrder, statementHolder);
                    resultSetWriter.write(rs);
                } finally {
                    if (rs != null)
                        rs.close();
                }
            }
        }

    } catch (SQLException e) {
        ServerLogger.getLogger().log(Level.WARNING, Tag.PRODUCT_PRODUCT_FAIL + CR_LF + "Statement: " + sqlOrder
                + CR_LF + "- sql order: " + sqlOrder + CR_LF + "- exception: " + e.toString());
        throw e;
    } finally {
        IOUtils.closeQuietly(out);

        if (statement != null) {
            statement.close();
        }
    }
}