Example usage for java.io InvalidClassException InvalidClassException

List of usage examples for java.io InvalidClassException InvalidClassException

Introduction

In this page you can find the example usage for java.io InvalidClassException InvalidClassException.

Prototype

public InvalidClassException(String reason) 

Source Link

Document

Report an InvalidClassException for the reason specified.

Usage

From source file:com.lts.core.commons.io.SerialKiller.java

@Override
protected Class<?> resolveClass(ObjectStreamClass serialInput) throws IOException, ClassNotFoundException {

    //Enforce SerialKiller's blacklist
    for (String blackRegExp : blacklist) {
        Pattern blackPattern = Pattern.compile(blackRegExp);
        Matcher blackMatcher = blackPattern.matcher(serialInput.getName());
        if (blackMatcher.find()) {
            throw new InvalidClassException("[!] Blocked by SerialKiller's blacklist '" + blackRegExp
                    + "'. Match found for '" + serialInput.getName() + "'");
        }/*from   ww w. j av a2  s  .co  m*/
    }

    //Enforce SerialKiller's whitelist
    boolean safeClass = false;
    for (String whiteRegExp : whitelist) {
        Pattern whitePattern = Pattern.compile(whiteRegExp);
        Matcher whiteMatcher = whitePattern.matcher(serialInput.getName());
        if (whiteMatcher.find()) {
            safeClass = true;
        }
    }
    if (!safeClass) {
        throw new InvalidClassException(
                "[!] Blocked by SerialKiller's whitelist. No match found for '" + serialInput.getName() + "'");
    }
    return super.resolveClass(serialInput);
}

From source file:org.nibblesec.tools.SerialKiller.java

@Override
protected Class<?> resolveClass(ObjectStreamClass serialInput) throws IOException, ClassNotFoundException {
    String[] blacklist = config.getStringArray("blacklist.regexp");
    String[] whitelist = config.getStringArray("whitelist.regexp");

    //Enforce SerialKiller's blacklist
    for (String blackRegExp : blacklist) {
        Pattern blackPattern = Pattern.compile(blackRegExp);
        Matcher blackMatcher = blackPattern.matcher(serialInput.getName());
        if (blackMatcher.find()) {
            throw new InvalidClassException("[!] Blocked by SerialKiller's blacklist '" + blackRegExp
                    + "'. Match found for '" + serialInput.getName() + "'");
        }/*w  w w .jav  a 2  s. c  o  m*/
    }

    //Enforce SerialKiller's whitelist
    boolean safeClass = false;
    for (String whiteRegExp : whitelist) {
        Pattern whitePattern = Pattern.compile(whiteRegExp);
        Matcher whiteMatcher = whitePattern.matcher(serialInput.getName());
        if (whiteMatcher.find()) {
            safeClass = true;
        }
    }
    if (!safeClass) {
        throw new InvalidClassException(
                "[!] Blocked by SerialKiller's whitelist. No match found for '" + serialInput.getName() + "'");
    }

    return super.resolveClass(serialInput);
}

From source file:org.apache.ibatis.executor.loader.AbstractSerialStateHolder.java

@SuppressWarnings("unchecked")
protected final Object readResolve() throws ObjectStreamException {
    /* Second run */
    if (this.userBean != null && this.userBeanBytes.length == 0) {
        return this.userBean;
    }//from   ww w. jav  a  2 s.  c  om

    /* First run */
    try (final ObjectInputStream in = new LookAheadObjectInputStream(
            new ByteArrayInputStream(this.userBeanBytes))) {
        this.userBean = in.readObject();
        this.unloadedProperties = (Map<String, ResultLoaderMap.LoadPair>) in.readObject();
        this.objectFactory = (ObjectFactory) in.readObject();
        this.constructorArgTypes = (Class<?>[]) in.readObject();
        this.constructorArgs = (Object[]) in.readObject();
    } catch (final IOException ex) {
        throw (ObjectStreamException) new StreamCorruptedException().initCause(ex);
    } catch (final ClassNotFoundException ex) {
        throw (ObjectStreamException) new InvalidClassException(ex.getLocalizedMessage()).initCause(ex);
    }

    final Map<String, ResultLoaderMap.LoadPair> arrayProps = new HashMap<>(this.unloadedProperties);
    final List<Class<?>> arrayTypes = Arrays.asList(this.constructorArgTypes);
    final List<Object> arrayValues = Arrays.asList(this.constructorArgs);

    return this.createDeserializationProxy(userBean, arrayProps, objectFactory, arrayTypes, arrayValues);
}

From source file:com.clustercontrol.plugin.factory.ModifyDbmsScheduler.java

private void setEntityInfo(DbmsSchedulerEntity entity, JobDetail jobDetail, Trigger trigger)
        throws InvalidClassException {

    entity.setMisfireInstr(trigger.getMisfireInstruction());
    entity.setDurable(jobDetail.isDurable());
    entity.setJobClassName(jobDetail.getJobDataMap().getString(ReflectionInvokerJob.KEY_CLASS_NAME));
    entity.setJobMethodName(jobDetail.getJobDataMap().getString(ReflectionInvokerJob.KEY_METHOD_NAME));

    if (trigger instanceof CronTrigger) {
        entity.setTriggerType(SchedulerPlugin.TriggerType.CRON.name());
        entity.setCronExpression(((CronTrigger) trigger).getCronExpression());
    } else if (trigger instanceof SimpleTrigger) {
        entity.setTriggerType(SchedulerPlugin.TriggerType.SIMPLE.name());
        entity.setRepeatInterval(((SimpleTrigger) trigger).getPeriod());
    }/* w w  w .j a v a2s . c  om*/

    entity.setTriggerState(TriggerState.VIRGIN.name());
    entity.setStartTime(trigger.getStartTime());
    entity.setEndTime(trigger.getEndTime());
    entity.setNextFireTime(trigger.getNextFireTime());
    entity.setPrevFireTime(trigger.getPreviousFireTime());

    @SuppressWarnings("unchecked")
    Class<? extends Serializable>[] argsType = (Class<? extends Serializable>[]) jobDetail.getJobDataMap()
            .get(ReflectionInvokerJob.KEY_ARGS_TYPE);
    Object[] args = (Object[]) jobDetail.getJobDataMap().get(ReflectionInvokerJob.KEY_ARGS);

    entity.setJobArgNum(args.length);
    for (int i = 0; i < args.length; i++) {

        String arg = "";
        if (m_log.isDebugEnabled())
            m_log.debug("arg[" + i + "]:" + args[i]);

        if (argsType[i] == String.class) {
            arg = (String) args[i];
        } else if (argsType[i] == Boolean.class) {
            arg = Boolean.toString((Boolean) args[i]);
        } else if (argsType[i] == Integer.class) {
            arg = Integer.toString((Integer) args[i]);
        } else if (argsType[i] == Long.class) {
            arg = Long.toString((Long) args[i]);
        } else if (argsType[i] == Short.class) {
            arg = Short.toString((Short) args[i]);
        } else if (argsType[i] == Float.class) {
            arg = Float.toString((Float) args[i]);
        } else if (argsType[i] == Double.class) {
            arg = Double.toString((Double) args[i]);
        } else {
            m_log.error("not support class");
            throw new InvalidClassException(argsType[i].getName());
        }
        String typeArg = argsType[i].getSimpleName() + ":" + arg;
        if (arg == null) {
            typeArg = "nullString";
        }
        if (m_log.isDebugEnabled())
            m_log.debug("typeArg[" + i + "]:" + typeArg);

        switch (i) {
        case 0:
            entity.setJobArg00(typeArg);
            break;
        case 1:
            entity.setJobArg01(typeArg);
            break;
        case 2:
            entity.setJobArg02(typeArg);
            break;
        case 3:
            entity.setJobArg03(typeArg);
            break;
        case 4:
            entity.setJobArg04(typeArg);
            break;
        case 5:
            entity.setJobArg05(typeArg);
            break;
        case 6:
            entity.setJobArg06(typeArg);
            break;
        case 7:
            entity.setJobArg07(typeArg);
            break;
        case 8:
            entity.setJobArg08(typeArg);
            break;
        case 9:
            entity.setJobArg09(typeArg);
            break;
        case 10:
            entity.setJobArg10(typeArg);
            break;
        case 11:
            entity.setJobArg11(typeArg);
            break;
        case 12:
            entity.setJobArg12(typeArg);
            break;
        case 13:
            entity.setJobArg13(typeArg);
            break;
        case 14:
            entity.setJobArg14(typeArg);
            break;
        default:
            m_log.error("arg count ng.");
        }
    }
}

From source file:org.sonar.server.notification.DefaultNotificationManagerTest.java

@Test
public void shouldNotFailWhenUnableToDeserialize() throws Exception {
    NotificationQueueDto dto1 = mock(NotificationQueueDto.class);
    when(dto1.toNotification()).thenThrow(new InvalidClassException("Pouet"));
    List<NotificationQueueDto> dtos = Arrays.asList(dto1);
    when(notificationQueueDao.selectOldest(1)).thenReturn(dtos);

    underTest = spy(underTest);//from   ww  w . j  av a  2  s . c  om
    assertThat(underTest.getFromQueue()).isNull();
    assertThat(underTest.getFromQueue()).isNull();

    verify(underTest, times(1)).logDeserializationIssue();
}

From source file:it.ecubecenter.processors.zookeeper.ZookeeperList.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();//from   ww w  .  j  av  a2  s  . co  m
    if (flowFile == null) {
        return;
    }
    final String outputFormat = context.getProperty(OUTPUT_FORMAT).getValue();
    renewKerberosAuthenticationIfNeeded(context);
    String zookeeperURL = context.getProperty(ZOOKEEPER_URL).getValue();
    ThreadsafeZookeeperClient conn = ThreadsafeZookeeperClient.getConnection(zookeeperURL);
    int trials = 3;
    while (trials > 0) {
        try {
            String zNode = context.getProperty(ZNODE_NAME).evaluateAttributeExpressions(flowFile).getValue();
            List<String> list = conn.listZNode(zNode);

            if (list == null) {
                session.getProvenanceReporter().route(flowFile, ZNODE_NOT_FOUND);
                session.transfer(flowFile, ZNODE_NOT_FOUND);
            } else {
                switch (context.getProperty(DESTINATION).getValue()) {
                case DESTINATION_CONTENT:
                    flowFile = session.write(flowFile, new OutputStreamCallback() {
                        @Override
                        public void process(OutputStream outputStream) throws IOException {
                            switch (outputFormat) {
                            case "csv":
                                StringBuilder sb = new StringBuilder();
                                boolean firstLine = true;
                                for (String zNode : list) {
                                    if (!firstLine) {
                                        sb.append(System.lineSeparator());
                                    }
                                    sb.append(zNode);
                                    firstLine = false;
                                }
                                outputStream.write(sb.toString().getBytes());
                                break;
                            case "json":
                                outputStream.write(objMapper.writeValueAsBytes(list));
                                break;
                            default:
                                throw new InvalidClassException("Unrecognized output format.");
                            }

                        }
                    });
                    session.getProvenanceReporter().fetch(flowFile, zookeeperURL + zNode);
                    flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(),
                            MIME_TYPE_MAP.get(outputFormat));
                    break;
                case DESTINATION_ATTRIBUTE:
                    switch (outputFormat) {
                    case "csv":
                        StringBuilder sb = new StringBuilder();
                        boolean firstLine = true;
                        for (String zN : list) {
                            if (!firstLine) {
                                sb.append(",");
                            }
                            sb.append(zN);
                            firstLine = false;
                        }
                        flowFile = session.putAttribute(flowFile, ATTIRUBTE_NAME, sb.toString());
                        break;
                    case "json":
                        flowFile = session.putAttribute(flowFile, ATTIRUBTE_NAME,
                                objMapper.writeValueAsString(list));
                        break;
                    default:
                        throw new InvalidClassException("Unrecognized output format.");
                    }
                    session.getProvenanceReporter().modifyAttributes(flowFile);
                    break;
                default:
                    throw new InvalidClassException("Unrecognized destination.");

                }

                session.transfer(flowFile, SUCCESS);
            }

            break;
        } catch (Exception e) {
            try {
                conn.close();
            } catch (InterruptedException e1) {
                getLogger().warn("Unable to close connection to Zookeeper.", e);
            }
            getLogger().warn("Error while listing from Zookeeper", e);
        }
        trials--;
    }
    if (trials == 0) {
        getLogger().error("Zookeeper operation failed 3 times");
        session.transfer(flowFile, FAILURE);
    }

}

From source file:ru.gkpromtech.exhibition.db.Table.java

public <F extends Entity, S extends Entity> List<Pair<F, S>> selectLinked(Class<F> f, Class<S> s,
        String selection, String[] selectionArgs, String orderBy)
        throws InvalidClassException, IllegalAccessException, InstantiationException {

    if (mFks.length != 2)
        throw new InvalidClassException("Entity " + mEntityClass.getName() + " is not a link");

    List<Pair<F, S>> result = new ArrayList<>();
    FkInfo fk1;/*from ww w .j a  v  a2 s. c  o m*/
    FkInfo fk2;

    if (mFks[0].entityClass.equals(f) && mFks[1].entityClass.equals(s)) {
        fk1 = mFks[0];
        fk2 = mFks[1];
    } else if (mFks[1].entityClass.equals(f) && mFks[0].entityClass.equals(s)) {
        //     ?   ?? ?
        fk1 = mFks[1];
        fk2 = mFks[0];
    } else {
        throw new InvalidClassException("Invalid classes passed as arguments");
    }

    Table<F> table1 = ((DbHelper) mSqlHelper).getTableFor(f);
    Table<S> table2 = ((DbHelper) mSqlHelper).getTableFor(s);

    StringBuilder query = new StringBuilder();
    for (String column : table1.mColumns) {
        query.append(",f.").append(column);
    }
    for (String column : table2.mColumns)
        query.append(",s.").append(column);
    query.replace(0, 1, "SELECT ");

    query.append("\nFROM ").append(mTableName).append(" t\nJOIN ").append(table1.mTableName).append(" f ON f.")
            .append(fk1.fkName).append(" = t.").append(fk1.fieldName).append("\nJOIN ")
            .append(table2.mTableName).append(" s ON s.").append(fk2.fkName).append(" = t.")
            .append(fk2.fieldName);
    if (selection != null)
        query.append("\nWHERE ").append(selection);
    if (orderBy != null)
        query.append("\nORDER BY ").append(orderBy);

    String queryString = query.toString();
    if (BuildConfig.DEBUG)
        Log.d("PP", queryString);

    SQLiteDatabase db = mSqlHelper.getReadableDatabase();
    Cursor cursor = db.rawQuery(queryString, selectionArgs);

    //noinspection TryFinallyCanBeTryWithResources
    try {
        while (cursor.moveToNext()) {
            F entity1 = f.newInstance();
            S entity2 = s.newInstance();
            for (int i = 0; i < table1.mFields.length; ++i)
                fillFieldValue(table1.mType[i], table1.mFields[i], entity1, cursor, i);
            for (int i = 0; i < table2.mFields.length; ++i)
                fillFieldValue(table2.mType[i], table2.mFields[i], entity2, cursor, table1.mFields.length + i);
            result.add(new Pair<>(entity1, entity2));
        }
    } finally {
        cursor.close();
        db.close();
    }

    return result;
}

From source file:org.apache.sling.distribution.packaging.impl.DistributionPackageUtils.java

private static ObjectInputStream getSafeObjectInputStream(InputStream inputStream) throws IOException {

    final Class[] acceptedClasses = new Class[] { HashMap.class, HashSet.class, String.class, String[].class,
            Long.class, Number.class, Boolean.class, Enum.class, DistributionRequestType.class };

    return new ObjectInputStream(inputStream) {
        @Override//from w w w  . j  a  va  2s  .  c om
        protected Class<?> resolveClass(ObjectStreamClass osc) throws IOException, ClassNotFoundException {
            String className = osc.getName();
            for (Class clazz : acceptedClasses) {
                if (clazz.getName().equals(className)) {
                    return super.resolveClass(osc);
                }
            }

            throw new InvalidClassException("Class name not accepted: " + className);
        }
    };

    // TODO: replace with the following lines when switching to commons-io-2.5
    //        return new ValidatingObjectInputStream(inputStream)
    //                .accept(acceptedClasses);
}

From source file:org.apache.rya.indexing.pcj.fluo.app.query.FluoQueryMetadataDAO.java

private AggregationMetadata.Builder readAggregationMetadataBuilder(final SnapshotBase sx, final String nodeId) {
    requireNonNull(sx);/*from  ww  w  . j a  va  2s. c o m*/
    requireNonNull(nodeId);

    // Fetch the values from the Fluo table.
    final String rowId = nodeId;
    final Map<Column, String> values = sx.gets(rowId, FluoQueryColumns.AGGREGATION_VARIABLE_ORDER,
            FluoQueryColumns.AGGREGATION_PARENT_NODE_ID, FluoQueryColumns.AGGREGATION_CHILD_NODE_ID,
            FluoQueryColumns.AGGREGATION_GROUP_BY_BINDING_NAMES);

    // Return an object holding them.
    final String varOrderString = values.get(FluoQueryColumns.AGGREGATION_VARIABLE_ORDER);
    final VariableOrder varOrder = new VariableOrder(varOrderString);

    final String parentNodeId = values.get(FluoQueryColumns.AGGREGATION_PARENT_NODE_ID);
    final String childNodeId = values.get(FluoQueryColumns.AGGREGATION_CHILD_NODE_ID);

    // Read the Group By variable order if one was present.
    final String groupByString = values.get(FluoQueryColumns.AGGREGATION_GROUP_BY_BINDING_NAMES);
    final VariableOrder groupByVars = groupByString.isEmpty() ? new VariableOrder()
            : new VariableOrder(groupByString.split(";"));

    // Deserialize the collection of AggregationElements.
    final Bytes aggBytes = sx.get(Bytes.of(nodeId.getBytes(Charsets.UTF_8)),
            FluoQueryColumns.AGGREGATION_AGGREGATIONS);
    final Collection<AggregationElement> aggregations;
    try (final ValidatingObjectInputStream vois = new ValidatingObjectInputStream(aggBytes.toInputStream())
    //// this is how you find classes that you missed in the vois.accept() list, below.
    // { @Override protected void invalidClassNameFound(String className) throws java.io.InvalidClassException {
    // System.out.println("vois.accept(" + className + ".class, ");};};
    ) {
        // These classes are allowed to be deserialized. Others throw InvalidClassException.
        vois.accept(java.util.ArrayList.class, java.lang.Enum.class, AggregationElement.class,
                AggregationType.class);
        final Object object = vois.readObject();
        if (!(object instanceof Collection<?>)) {
            throw new InvalidClassException(
                    "Object read was not of type Collection. It was: " + object.getClass());
        }
        aggregations = (Collection<AggregationElement>) object;
    } catch (final IOException | ClassNotFoundException e) {
        throw new RuntimeException(
                "Problem encountered while reading AggregationMetadata from the Fluo table. Unable "
                        + "to deserialize the AggregationElements from a byte[].",
                e);
    }

    final AggregationMetadata.Builder builder = AggregationMetadata.builder(nodeId).setVarOrder(varOrder)
            .setParentNodeId(parentNodeId).setChildNodeId(childNodeId).setGroupByVariableOrder(groupByVars);

    for (final AggregationElement aggregation : aggregations) {
        builder.addAggregation(aggregation);
    }

    return builder;
}