Search in sources :

Example 16 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class Get70 method cmdExecute.

@Override
public void cmdExecute(Message clientMessage, ServerConnection serverConnection, long startparam) throws IOException {
    long start = startparam;
    Part regionNamePart = null, keyPart = null, valuePart = null;
    String regionName = null;
    Object callbackArg = null, key = null;
    CachedRegionHelper crHelper = serverConnection.getCachedRegionHelper();
    CacheServerStats stats = serverConnection.getCacheServerStats();
    StringId errMessage = null;
    serverConnection.setAsTrue(REQUIRES_RESPONSE);
    // requiresResponse = true;
    {
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incReadGetRequestTime(start - oldStart);
    }
    // Retrieve the data from the message parts
    int parts = clientMessage.getNumberOfParts();
    regionNamePart = clientMessage.getPart(0);
    keyPart = clientMessage.getPart(1);
    // valuePart = null; (redundant assignment)
    if (parts > 2) {
        valuePart = clientMessage.getPart(2);
        try {
            callbackArg = valuePart.getObject();
        } catch (Exception e) {
            writeException(clientMessage, e, false, serverConnection);
            // responded = true;
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
    }
    regionName = regionNamePart.getString();
    try {
        key = keyPart.getStringOrObject();
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        // responded = true;
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Received 7.0 get request ({} bytes) from {} for region {} key {} txId {}", serverConnection.getName(), clientMessage.getPayloadLength(), serverConnection.getSocketString(), regionName, key, clientMessage.getTransactionId());
    }
    // Process the get request
    if (key == null || regionName == null) {
        if ((key == null) && (regionName == null)) {
            errMessage = LocalizedStrings.Request_THE_INPUT_REGION_NAME_AND_KEY_FOR_THE_GET_REQUEST_ARE_NULL;
        } else if (key == null) {
            errMessage = LocalizedStrings.Request_THE_INPUT_KEY_FOR_THE_GET_REQUEST_IS_NULL;
        } else if (regionName == null) {
            errMessage = LocalizedStrings.Request_THE_INPUT_REGION_NAME_FOR_THE_GET_REQUEST_IS_NULL;
        }
        String s = errMessage.toLocalizedString();
        logger.warn("{}: {}", serverConnection.getName(), s);
        writeErrorResponse(clientMessage, MessageType.REQUESTDATAERROR, s, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    Region region = serverConnection.getCache().getRegion(regionName);
    if (region == null) {
        String reason = LocalizedStrings.Request__0_WAS_NOT_FOUND_DURING_GET_REQUEST.toLocalizedString(regionName);
        writeRegionDestroyedEx(clientMessage, regionName, reason, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    GetOperationContext getContext = null;
    try {
        // for integrated security
        this.securityService.authorizeRegionRead(regionName, key.toString());
        AuthorizeRequest authzRequest = serverConnection.getAuthzRequest();
        if (authzRequest != null) {
            getContext = authzRequest.getAuthorize(regionName, key, callbackArg);
            callbackArg = getContext.getCallbackArg();
        }
    } catch (NotAuthorizedException ex) {
        writeException(clientMessage, ex, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    // Get the value and update the statistics. Do not deserialize
    // the value if it is a byte[].
    Entry entry;
    try {
        entry = getEntry(region, key, callbackArg, serverConnection);
    } catch (Exception e) {
        writeException(clientMessage, e, false, serverConnection);
        serverConnection.setAsTrue(RESPONDED);
        return;
    }
    @Retained final Object originalData = entry.value;
    Object data = originalData;
    try {
        boolean isObject = entry.isObject;
        VersionTag versionTag = entry.versionTag;
        boolean keyNotPresent = entry.keyNotPresent;
        try {
            AuthorizeRequestPP postAuthzRequest = serverConnection.getPostAuthzRequest();
            if (postAuthzRequest != null) {
                try {
                    getContext = postAuthzRequest.getAuthorize(regionName, key, data, isObject, getContext);
                    GetOperationContextImpl gci = (GetOperationContextImpl) getContext;
                    Object newData = gci.getRawValue();
                    if (newData != data) {
                        // user changed the value
                        isObject = getContext.isObject();
                        data = newData;
                    }
                } finally {
                    if (getContext != null) {
                        ((GetOperationContextImpl) getContext).release();
                    }
                }
            }
        } catch (NotAuthorizedException ex) {
            writeException(clientMessage, ex, false, serverConnection);
            serverConnection.setAsTrue(RESPONDED);
            return;
        }
        // post process
        data = this.securityService.postProcess(regionName, key, data, entry.isObject);
        long oldStart = start;
        start = DistributionStats.getStatTime();
        stats.incProcessGetTime(start - oldStart);
        if (region instanceof PartitionedRegion) {
            PartitionedRegion pr = (PartitionedRegion) region;
            if (pr.getNetworkHopType() != PartitionedRegion.NETWORK_HOP_NONE) {
                writeResponseWithRefreshMetadata(data, callbackArg, clientMessage, isObject, serverConnection, pr, pr.getNetworkHopType(), versionTag, keyNotPresent);
                pr.clearNetworkHopData();
            } else {
                writeResponse(data, callbackArg, clientMessage, isObject, versionTag, keyNotPresent, serverConnection);
            }
        } else {
            writeResponse(data, callbackArg, clientMessage, isObject, versionTag, keyNotPresent, serverConnection);
        }
    } finally {
        OffHeapHelper.release(originalData);
    }
    serverConnection.setAsTrue(RESPONDED);
    if (logger.isDebugEnabled()) {
        logger.debug("{}: Wrote get response back to {} for region {} {}", serverConnection.getName(), serverConnection.getSocketString(), regionName, entry);
    }
    stats.incWriteGetResponseTime(DistributionStats.getStatTime() - start);
}
Also used : AuthorizeRequest(org.apache.geode.internal.security.AuthorizeRequest) AuthorizeRequestPP(org.apache.geode.internal.security.AuthorizeRequestPP) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) GetOperationContextImpl(org.apache.geode.cache.operations.internal.GetOperationContextImpl) NotAuthorizedException(org.apache.geode.security.NotAuthorizedException) IOException(java.io.IOException) GetOperationContext(org.apache.geode.cache.operations.GetOperationContext) CachedRegionHelper(org.apache.geode.internal.cache.tier.CachedRegionHelper) StringId(org.apache.geode.i18n.StringId) Retained(org.apache.geode.internal.offheap.annotations.Retained) CacheServerStats(org.apache.geode.internal.cache.tier.sockets.CacheServerStats) Part(org.apache.geode.internal.cache.tier.sockets.Part) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion) VersionTag(org.apache.geode.internal.cache.versions.VersionTag) LocalRegion(org.apache.geode.internal.cache.LocalRegion) Region(org.apache.geode.cache.Region) PartitionedRegion(org.apache.geode.internal.cache.PartitionedRegion)

Example 17 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class BasicI18nJUnitTest method testSetLocale.

@Test
public void testSetLocale() {
    // Verify we are starting in a known state
    assertTrue(DEFAULT_LOCALE.equals(getCurrentLocale()));
    StringId.setLocale(Locale.FRANCE);
    assertTrue(Locale.FRANCE.equals(getCurrentLocale()));
    StringId.setLocale(Locale.FRANCE);
    assertTrue(Locale.FRANCE.equals(getCurrentLocale()));
    StringId s = LocalizedStrings.UNSUPPORTED_AT_THIS_TIME;
    assertTrue(s.toString().equals(s.toLocalizedString()));
    StringId.setLocale(Locale.JAPAN);
    assertTrue(Locale.JAPAN.equals(getCurrentLocale()));
    if (getActiveResourceBundle().usingRawMode()) {
        assertTrue(s.toString().equals(s.toLocalizedString()));
    } else {
        assertFalse(s.toString().equals(s.toLocalizedString()));
    }
}
Also used : StringId(org.apache.geode.i18n.StringId) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 18 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class BasicI18nJUnitTest method verifyStringsAreProperlyEscaped.

/**
   * Check that the "raw" string matches the "formatted" string after taking into account known
   * changes due to the fomatting process. For example: <code>
   * "I''m using a contraction." should become "I'm using a contraction."
   * </code>
   */
private void verifyStringsAreProperlyEscaped(Locale loc) {
    StringId.setLocale(loc);
    final Set<StringId> misquoted = new HashSet<StringId>();
    final Object[] identityArgs = new Object[100];
    for (int index = 0; index < identityArgs.length; index++) {
        identityArgs[index] = index;
    }
    final AbstractStringIdResourceBundle rb = getActiveResourceBundle();
    for (StringId instance : getAllStringIds()) {
        String raw = rb.getString(instance);
        String altered = raw.replaceAll("''", "'");
        altered = altered.replaceAll("\\{([0-9]+)[^\\}]*\\}", "$1");
        if (!rb.usingRawMode()) {
            altered = "msgID " + ((StringId) instance).id + ": " + altered;
        }
        String formatted = null;
        try {
            formatted = instance.toLocalizedString(identityArgs);
        } catch (IllegalArgumentException iae) {
            String testName = this.getClass().getName().replaceAll("\\.", "/") + ".class";
            String exMsg = "Improper message id=" + ((StringId) instance).id + "\n" + "Usually this is caused by an unmatched or nested \"{\"\n" + "Examples:\t\"{0]\" or \"{ {0} }\"\n" + "This is just the first failure, it is in your interest" + " to rebuild and run just this one test.\n" + "build.sh run-java-tests -Djunit.testcase=" + testName;
            throw new AssertionError(exMsg, iae);
        }
        if (!altered.equals(formatted)) {
            System.err.println("altered:   " + altered);
            System.err.println("formatted: " + formatted);
            misquoted.add(instance);
        }
    }
    if (!misquoted.isEmpty()) {
        StringBuffer err = new StringBuffer();
        err.append("These errors are usually resolved by replacing ");
        err.append("\"'\" with \"''\".\n");
        err.append("If the error is in the non-english version then ");
        err.append("alter the text in StringIdResouceBundle_{lang}.txt.\n");
        err.append("The following misquoted StringIds were found:");
        for (StringId i : misquoted) {
            err.append("\n").append("StringId id=").append(((StringId) i).id).append(" : text=\"").append(i.getRawText()).append("\"");
        }
        fail(err.toString());
    }
}
Also used : StringId(org.apache.geode.i18n.StringId) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 19 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class BasicI18nJUnitTest method testVerifyStringIdsAreUnique.

/**
   * Use reflection to find all instances of StringId defined within the classes listed in
   * StringIdDefiningClasses and verify there are not any duplicate indexes used.
   */
@Test
public void testVerifyStringIdsAreUnique() {
    final Set<Integer> allStringIds = new HashSet<Integer>(3000);
    // Save all duplicate ids and report them at the end
    final Set<StringId> duplicates = new HashSet<StringId>();
    for (StringId instance : getAllStringIds()) {
        boolean isUnique = allStringIds.add(((StringId) instance).id);
        // between String bundles to minimize compiler dependencies.
        if ((!isUnique) && ((StringId) instance).id >= 1024) {
            boolean status = duplicates.add(instance);
            assertTrue("Failed to add " + instance + "to the list of" + " duplicates because of duplicate duplicates", status);
        }
    }
    if (!duplicates.isEmpty()) {
        StringBuilder err = new StringBuilder();
        err.append("The following duplicate StringIds were found:");
        for (StringId i : duplicates) {
            err.append("\n").append(((StringId) i).id).append(" : ").append(i.getRawText());
        }
        fail(err.toString() + "\nSearched in " + getStringIdDefiningClasses());
    }
}
Also used : StringId(org.apache.geode.i18n.StringId) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Test(org.junit.Test) IntegrationTest(org.apache.geode.test.junit.categories.IntegrationTest)

Example 20 with StringId

use of org.apache.geode.i18n.StringId in project geode by apache.

the class BasicI18nJUnitTest method getAllStringIds.

/**
   * Get all of the StringId instances via reflection.
   * 
   * @return a set of all StringId declarations within the product
   */
private Set<StringId> getAllStringIds() {
    final Set<StringId> allStringIds = new HashSet<StringId>();
    for (String className : getStringIdDefiningClasses()) {
        try {
            Class<?> c = Class.forName(className);
            Field[] fields = c.getDeclaredFields();
            final String msg = "Found no StringIds in " + className;
            assertTrue(msg, fields.length > 0);
            for (Field f : fields) {
                f.setAccessible(true);
                StringId instance = (StringId) f.get(null);
                allStringIds.add(instance);
            }
        } catch (ClassNotFoundException cnfe) {
            throw new AssertionError(cnfe.toString(), cnfe);
        } catch (Exception e) {
            String exMsg = "Reflection attempt failed while attempting to find all" + " StringId instances. ";
            throw new AssertionError(exMsg + e.toString(), e);
        }
    }
    return allStringIds;
}
Also used : Field(java.lang.reflect.Field) StringId(org.apache.geode.i18n.StringId) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

StringId (org.apache.geode.i18n.StringId)43 IOException (java.io.IOException)14 AuthorizeRequest (org.apache.geode.internal.security.AuthorizeRequest)11 LocalRegion (org.apache.geode.internal.cache.LocalRegion)10 CachedRegionHelper (org.apache.geode.internal.cache.tier.CachedRegionHelper)8 Part (org.apache.geode.internal.cache.tier.sockets.Part)8 TimeoutException (org.apache.geode.cache.TimeoutException)6 HashSet (java.util.HashSet)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 List (java.util.List)4 CancelException (org.apache.geode.CancelException)4 InterestResultPolicy (org.apache.geode.cache.InterestResultPolicy)4 RegisterInterestOperationContext (org.apache.geode.cache.operations.RegisterInterestOperationContext)4 CqClosedException (org.apache.geode.cache.query.CqClosedException)4 CqException (org.apache.geode.cache.query.CqException)4 CqExistsException (org.apache.geode.cache.query.CqExistsException)4 QueryException (org.apache.geode.cache.query.QueryException)4 RegionNotFoundException (org.apache.geode.cache.query.RegionNotFoundException)4 LinkedHashSet (java.util.LinkedHashSet)3