/*
(non-Javadoc)
@see org.fcrepo.server.management.FedoraAPIMMTOM#ingest(javax.activation.
DataHandler objectXML ,)String format ,)String logMessage )*
194953
@Override
    public String ingest(DataHandler objectXML, String format, String logMessage) {
        LOG.debug("start: ingest");
        assertInitialized();
        try {
            // always gens pid, unless pid in stream starts with "test:" "demo:"
            // or other prefix that is configured in the retainPIDs parameter of
            // fedora.fcfg
            MessageContext ctx = context.getMessageContext();
            InputStream byteStream = null;
            if (objectXML != null) {
                byteStream = objectXML.getInputStream();
            }
            return m_management.ingest(ReadOnlyContext.getSoapContext(ctx),
                                       byteStream,
                                       logMessage,
                                       format,
                                       "UTF-8",
                                       "new");
        } catch (Throwable th) {
            LOG.error("Error ingesting", th);
            throw CXFUtility.getFault(th);
        } finally {
            LOG.debug("end: ingest");
        }
    }
410305
@Override
    public void trace(String format, Object arg) {
        if (logger.isTraceEnabled()) {
            FormattingTuple ft = MessageFormatter.format(format, arg);
            logger.trace(ft.getMessage(), ft.getThrowable());
        }
    }
1223454
@Warmup(iterations = 5)
    @Measurement(iterations = 5)
    @Benchmark
    public void logstashStructuredParametrizedMessageLogging1Call() {
        loggerLogstashParametrizedMessage.info("Event with double={} and boolean={}", value("varDouble", 1.2), value("varBoolean", false));
    }
1024275
public void w(final String msg) {
        logMgr.log(tag, LogLevelConst.WARNING, msg, null);
    }
788948
@Override
  public String doLayout(ILoggingEvent event) {

    // Format message
    String msg = super.doLayout(event).trim();
    // prevent log forging
    msg = preventLogForging(msg);

    // Formatting of exception, remove line breaks
    IThrowableProxy throwableProxy = event.getThrowableProxy();
    if (throwableProxy != null) {
      StackTraceElementProxy[] s = throwableProxy.getStackTraceElementProxyArray();
      if (s != null && s.length > 0) {
        // Performance: Initialize StringBuilder with (number of StackTrace-Elements + 1)*50 (+1 for Message)
        StringBuilder sb = new StringBuilder(s.length * BUFFER_PER_LINE);
        sb.append(msg);

        int len = s.length;
        for (int i = 0; i < len; i++) {
          sb.append(LINE_SEP).append(s[i]);
        }
        msg = sb.toString();
      }
    }
    return msg + NEWLINE;
  }
842818
@Override
	public void setObject(Serializable object) throws JMSException
    {
    	if (bodyIsReadOnly)
    		throw new MessageNotWriteableException("Message body is read-only");
    	
    	assertDeserializationLevel(MessageSerializationLevel.FULL);
    	
        if (object == null)
        {
            body = null;
            return;
        }
        
        try
        {
        	body = SerializationTools.toByteArray(object);
        }
        catch (Exception e)
        {
        	throw new FFMQException("Cannot serialize object message body","MESSAGE_ERROR",e);
        }
    }
36664
@Override
  public void logMessage(LogLevel logLevel, String message, Class clazz, String methodName) {
    Logger logger = Logger.getLogger(clazz.getName());
    logger.logp(convertToJDK14Level(logLevel), clazz.getName(), methodName, message);
  }
1197399
protected void logSoapMessage(String logMessage, SoapMessage soapMessage, boolean incoming) throws TransformerException {
        Transformer transformer = createIndentingTransformer();
        StringWriter writer = new StringWriter();
        
        transformer.transform(soapMessage.getEnvelope().getSource(), new StreamResult(writer));
        logMessage(logMessage, XMLUtils.prettyPrint(writer.toString()), incoming);
    }
977160
protected void logWebServiceMessage(String logMessage, WebServiceMessage message, boolean incoming) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        
        try {
            message.writeTo(os);
            logMessage(logMessage, os.toString(), incoming);
        } catch (IOException e) {
            log.warn("Unable to log WebService message", e);
        }
    }
684302
def ingest(self, co, classname=None, code_objects={}, show_asm=None):
        
        tokens, customize = scan.Scanner21.ingest(self, co, classname, code_objects, show_asm)
        for t in tokens:
            if t.op == self.opc.UNPACK_LIST:
                t.kind = 'UNPACK_LIST_%d' % t.attr
            pass
        return tokens, customize
908820
public static void main(String[] args) {
        System.setProperty("java.awt.headless", "true");
        try {
            if (args.length < 1) {
                Ingest.badArgs("No arguments entered!");
            }
            String context = Constants.FEDORA_DEFAULT_APP_CONTEXT;
            PrintStream log = null;
            File logFile = null;
            String logRootName = null;
            IngestCounter counter = new IngestCounter();
            char kind = args[0].toLowerCase().charAt(0);
            if (kind == 'f') {
                // USAGE: fedora-ingest f[ile] path format targetHost:targetProtocol targetUser targetPassword targetProtocol [log] [context]
                if (args.length < 7 || args.length > 9) {
                    Ingest.badArgs("Wrong number of arguments for file ingest.");
                    System.out
                            .println("USAGE: fedora-ingest f[ile] path format targetHost:targetProtocol targetUser targetPassword targetProtocol [log] [context]");
                }
                File f = new File(args[1]);
                String ingestFormat = args[2];
                String logMessage = null;

                if (args.length == 8) {
                    logMessage = args[7];
                }

                if (args.length == 9 && !args[8].isEmpty()) {
                    context = args[8];
                }

                String protocol = args[6];
                String[] hp = args[3].split(":");

                // ******************************************
                // NEW: use new client utility class
                String baseURL =
                        protocol + "://" + hp[0] + ":"
                                + Integer.parseInt(hp[1]) + "/" + context;
                FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
                FedoraAPIAMTOM targetRepoAPIA = fc.getAPIAMTOM();
                FedoraAPIMMTOM targetRepoAPIM = fc.getAPIMMTOM();
                fc.shutdown();
                //*******************************************

                String pid =
                        Ingest.oneFromFile(f,
                                           ingestFormat,
                                           targetRepoAPIA,
                                           targetRepoAPIM,
                                           logMessage);
                if (pid == null) {
                    System.out.print("ERROR: ingest failed for file: "
                            + args[1]);
                } else {
                    System.out.println("Ingested pid: " + pid);
                }
            } else if (kind == 'd') {
                // USAGE: fedora-ingest d[ir] path format targetHost:targetPort targetUser targetPassword targetProtocol [log] [context]
                if (args.length < 7 || args.length > 9) {
                    Ingest.badArgs("Wrong number of arguments (" + args.length
                            + ") for directory ingest.");
                    System.out
                            .println("USAGE: fedora-ingest d[ir] path format targetHost:targetPort targetUser targetPassword targetProtocol [log] [context]");
                }
                File d = new File(args[1]);
                String ingestFormat = args[2];
                String logMessage = null;

                if (args.length == 8) {
                    logMessage = args[7];
                }

                if (args.length == 9 && !args[8].isEmpty()) {
                    context = args[8];
                }

                String protocol = args[6];
                String[] hp = args[3].split(":");

                // ******************************************
                // NEW: use new client utility class
                String baseURL =
                        protocol + "://" + hp[0] + ":"
                                + Integer.parseInt(hp[1]) + "/" + context;
                FedoraClient fc = new FedoraClient(baseURL, args[4], args[5]);
                FedoraAPIAMTOM targetRepoAPIA = fc.getAPIAMTOM();
                FedoraAPIMMTOM targetRepoAPIM = fc.getAPIMMTOM();
                //*******************************************

                logRootName = "ingest-from-dir";
                logFile = IngestLogger.newLogFile(logRootName);
                log =
                        new PrintStream(new FileOutputStream(logFile),
                                        true,
                                        "UTF-8");
                IngestLogger.openLog(log, logRootName);
                Ingest.multiFromDirectory(d,
                                          ingestFormat,
                                          targetRepoAPIA,
                                          targetRepoAPIM,
                                          logMessage,
                                          log,
                                          counter);
                IngestLogger.closeLog(log, logRootName);
                summarize(counter, logFile);
            } else if (kind == 'r') {
                // USAGE: fedora-ingest r[epos] sourceHost:sourcePort sourceUser sourcePassword pid|* targetHost:targetPort targetUser targetPassword sourceProtocol targetProtocol [log] [context]
                if (args.length < 10 || args.length > 12) {
                    Ingest.badArgs("Wrong number of arguments for repository ingest.");
                }
                String logMessage = null;
                if (args.length == 11) {
                    logMessage = args[10];
                }

                if (args.length == 12 && !args[11].isEmpty()) {
                    context = args[11];
                }
                //Source repository
                String[] shp = args[1].split(":");
                String source_host = shp[0];
                String source_port = shp[1];
                String source_user = args[2];
                String source_password = args[3];
                String source_protocol = args[8];

                // ******************************************
                // NEW: use new client utility class
                String sourceBaseURL =
                        source_protocol + "://" + source_host + ":"
                                + Integer.parseInt(source_port) + "/" + context;
                FedoraClient sfc =
                        new FedoraClient(sourceBaseURL,
                                         source_user,
                                         source_password);
                FedoraAPIAMTOM sourceRepoAPIA = sfc.getAPIAMTOM();
                FedoraAPIMMTOM sourceRepoAPIM = sfc.getAPIMMTOM();
                //*******************************************

                //Target repository
                String[] thp = args[5].split(":");
                String target_host = thp[0];
                String target_port = thp[1];
                String target_user = args[6];
                String target_password = args[7];
                String target_protocol = args[9];

                // ******************************************
                // NEW: use new client utility class
                String targetBaseURL =
                        target_protocol + "://" + target_host + ":"
                                + Integer.parseInt(target_port) + "/" + context;
                FedoraClient tfc =
                        new FedoraClient(targetBaseURL,
                                         target_user,
                                         target_password);
                FedoraAPIAMTOM targetRepoAPIA = tfc.getAPIAMTOM();
                FedoraAPIMMTOM targetRepoAPIM = tfc.getAPIMMTOM();
                //*******************************************

                // Determine export format
                RepositoryInfo repoinfo = sourceRepoAPIA.describeRepository();
                System.out
                        .println("Ingest: exporting from a source repo version "
                                + repoinfo.getRepositoryVersion());
                String sourceExportFormat = getExportFormat(repoinfo);
                System.out.println("Ingest: source repo is using "
                        + sourceExportFormat + " export format.");

                if (args[4].indexOf(":") != -1) {
                    // single object
                    String successfulPID =
                            Ingest.oneFromRepository(sourceRepoAPIA,
                                                     sourceRepoAPIM,
                                                     sourceExportFormat,
                                                     args[4],
                                                     targetRepoAPIA,
                                                     targetRepoAPIM,
                                                     logMessage);
                    if (successfulPID == null) {
                        System.out
                                .print("ERROR: ingest from repo failed for pid="
                                        + args[4]);
                    } else {
                        System.out.println("Ingested pid: " + successfulPID);
                    }
                } else {
                    // multi-object
                    //hp=args[1].split(":");
                    logRootName = "ingest-from-repository";
                    logFile = IngestLogger.newLogFile(logRootName);
                    log =
                            new PrintStream(new FileOutputStream(logFile),
                                            true,
                                            "UTF-8");
                    IngestLogger.openLog(log, logRootName);
                    Ingest.multiFromRepository(source_protocol,
                                               source_host,
                                               Integer.parseInt(source_port),
                                               sourceRepoAPIA,
                                               sourceRepoAPIM,
                                               sourceExportFormat,
                                               targetRepoAPIA,
                                               targetRepoAPIM,
                                               logMessage,
                                               log,
                                               counter);
                    IngestLogger.closeLog(log, logRootName);
                    summarize(counter, logFile);
                }

            } else {
                Ingest.badArgs("First argument must start with f, d, or r.");
            }
        } catch (Exception e) {
            System.err.print("Error  : ");
            if (e.getMessage() == null) {
                e.printStackTrace();
            } else {
                System.err.print(e.getMessage());
            }
            System.err.println();
            if (Ingest.LAST_PATH != null) {
                System.out.println("(Last attempted file was "
                        + Ingest.LAST_PATH + ")");
            }
        }
    }
1027831
@Override
    public void processXML()
                    throws InjectionException
    {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "processXML : " + this);

        List<? extends MailSession> mailSessionDefinitions = ivNameSpaceConfig.getJNDIEnvironmentRefs(MailSession.class);

        if (mailSessionDefinitions != null)
        {
            for (MailSession mailSession : mailSessionDefinitions)
            {
                String jndiName = mailSession.getName();
                InjectionBinding<MailSessionDefinition> injectionBinding = ivAllAnnotationsCollection.get(jndiName);
                MailSessionDefinitionInjectionBinding binding;

                if (injectionBinding != null)
                {
                    binding = (MailSessionDefinitionInjectionBinding) injectionBinding;
                }
                else
                {
                    binding = new MailSessionDefinitionInjectionBinding(jndiName, ivNameSpaceConfig);
                    addInjectionBinding(binding);
                }

                binding.mergeXML(mailSession);
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "processXML : " + this);

    }
816732
private static String serializedGraphForMessage(final Message message, final Resource subject) throws IOException {

        // serialize triples
        final ByteArrayOutputStream serializedGraph = new ByteArrayOutputStream();
        final Model model = createDefaultModel();

        // get info from jms message headers
        @SuppressWarnings("unchecked")
        final List<String> eventType = message.getHeader(FCREPO_EVENT_TYPE, emptyList(), List.class);
        final String dateTime = message.getHeader(FCREPO_DATE_TIME, EMPTY_STRING, String.class);
        @SuppressWarnings("unchecked")
        final List<String> agents = message.getHeader(FCREPO_AGENT, emptyList(), List.class);
        @SuppressWarnings("unchecked")
        final List<String> resourceTypes = message.getHeader(FCREPO_RESOURCE_TYPE, emptyList(), List.class);
        final String identifier = message.getHeader(FCREPO_URI, EMPTY_STRING, String.class);
        final Optional<String> premisType = getAuditEventType(eventType, resourceTypes);

        model.add( model.createStatement(subject, type, INTERNAL_EVENT) );
        model.add( model.createStatement(subject, type, PREMIS_EVENT) );
        model.add( model.createStatement(subject, type, PROV_EVENT) );

        // basic event info
        model.add( model.createStatement(subject, PREMIS_TIME, createTypedLiteral(dateTime, XSDdateTime)) );
        model.add( model.createStatement(subject, PREMIS_OBJ, createResource(identifier)) );

        agents.forEach(agent -> {
            model.add( model.createStatement(subject, PREMIS_AGENT, createTypedLiteral(agent, XSDstring)) );
        });

        premisType.ifPresent(rdfType -> {
            model.add(model.createStatement(subject, PREMIS_TYPE, createResource(rdfType)));
        });

        write(serializedGraph, model, NTRIPLES);
        return serializedGraph.toString("UTF-8");
    }
31328
func (m *metricExtractionSink) Ingest(span *ssf.SSFSpan) error {
	var metricsCount int
	defer func() {
		atomic.AddInt64(&m.metricsGenerated, int64(metricsCount))
		atomic.AddInt64(&m.spansProcessed, 1)
	}()
	metrics, err := samplers.ConvertMetrics(span)
	if err != nil {
		if _, ok := err.(samplers.InvalidMetrics); ok {
			m.log.WithError(err).
				Warn("Could not parse metrics from SSF Message")
			m.SendSample(ssf.Count("ssf.error_total", 1, map[string]string{
				"packet_type": "ssf_metric",
				"step":        "extract_metrics",
				"reason":      "invalid_metrics",
			}))
		} else {
			m.log.WithError(err).Error("Unexpected error extracting metrics from SSF Message")
			m.SendSample(ssf.Count("ssf.error_total", 1, map[string]string{
				"packet_type": "ssf_metric",
				"step":        "extract_metrics",
				"reason":      "unexpected_error",
				"error":       err.Error(),
			}))
			return err
		}
	}
	metricsCount += len(metrics)
	m.sendMetrics(metrics)

	if err := protocol.ValidateTrace(span); err != nil {
		return err
	}
	// If we made it here, we are dealing with a fully-fledged
	// trace span, not just a mere carrier for Samples:

	indicatorMetrics, err := samplers.ConvertIndicatorMetrics(span, m.indicatorSpanTimerName, m.objectiveSpanTimerName)
	if err != nil {
		m.log.WithError(err).
			WithField("span_name", span.Name).
			Warn("Couldn't extract indicator metrics for span")
		return err
	}
	metricsCount += len(indicatorMetrics)

	spanMetrics, err := samplers.ConvertSpanUniquenessMetrics(span, 0.01)
	if err != nil {
		m.log.WithError(err).
			WithField("span_name", span.Name).
			Warn("Couldn't extract uniqueness metrics for span")
		return err
	}
	metricsCount += len(spanMetrics)

	m.sendMetrics(append(indicatorMetrics, spanMetrics...))
	return nil
}
1302977
@Override
    public String purgeObject(String pid, String logMessage, boolean force) {
        LOG.debug("start: purgeObject, {}", pid);
        assertInitialized();
        try {
            MessageContext ctx = context.getMessageContext();
            return DateUtility.convertDateToString(m_management
                    .purgeObject(ReadOnlyContext.getSoapContext(ctx),
                                 pid,
                                 logMessage));
        } catch (Throwable th) {
            LOG.error("Error purging object", th);
            throw CXFUtility.getFault(th);
        } finally {
            LOG.debug("end: purgeObject, {}", pid);
        }
    }
206899
public String ingest(Context context,
                         InputStream serialization,
                         String logMessage,
                         String format,
                         String encoding,
                         String pid) throws ServerException {
        try {
            CreatorJournalEntry cje =
                    new CreatorJournalEntry(METHOD_INGEST, context);
            cje.addArgument(ARGUMENT_NAME_SERIALIZATION, serialization);
            cje.addArgument(ARGUMENT_NAME_LOG_MESSAGE, logMessage);
            cje.addArgument(ARGUMENT_NAME_FORMAT, format);
            cje.addArgument(ARGUMENT_NAME_ENCODING, encoding);
            cje.addArgument(ARGUMENT_NAME_NEW_PID, pid);
            return (String) cje.invokeAndClose(delegate, writer);
        } catch (JournalException e) {
            throw new GeneralException("Problem creating the Journal", e);
        }
    }
1205311
@Override
    public void xmlWriteOn(FormattedWriter writer) throws IOException
    {
        // Restore an un-cached message to we can dump its state
        if (msg == null)
            getJSMessage(true);

        try
        {
            if (msg != null)
            {
                writer.newLine();
                writer.taggedValue("JsMessage", msg.getClass().getName());
                writer.newLine();
                writer.taggedValue("systemMessageId", msg.getSystemMessageId());

                if (msg instanceof JsApiMessage)
                {
                    writer.newLine();
                    writer.taggedValue("APIMessageId", ((JsApiMessage) msg).getApiMessageId());
                    writer.newLine();
                    writer.taggedValue("APICorrelId", ((JsApiMessage) msg).getCorrelationId());
                }
                else
                {
                    if (msg.getApiMessageIdAsBytes() != null)
                    {
                        writer.newLine();
                        writer.taggedValue("APIMessageId", new String(msg.getApiMessageIdAsBytes()));
                    }
                    if (msg.getCorrelationIdAsBytes() != null)
                    {
                        writer.newLine();
                        writer.taggedValue("APICorrelId", new String(msg.getCorrelationIdAsBytes()));
                    }
                }

                writer.newLine();
                writer.taggedValue("putTime", new Date(msg.getTimestamp()));

                // If this MessageItem is sitting on an xmit ItemStream then we're probably
                // going to be interested in the GD data in the message.
                try
                {
                    ItemStream is = getItemStream();
                    if (is instanceof PtoPXmitMsgsItemStream)
                    {
                        writer.newLine();
                        writer.startTag("xmitData");
                        writer.indent();

                        writer.newLine();
                        writer.taggedValue("startTick", msg.getGuaranteedValueStartTick());
                        writer.newLine();
                        writer.taggedValue("endTick", msg.getGuaranteedValueEndTick());
                        writer.newLine();
                        writer.taggedValue("priority", msg.getPriority());
                        writer.newLine();
                        writer.taggedValue("reliability", msg.getReliability());
                        writer.newLine();
                        writer.taggedValue("streamId", msg.getGuaranteedStreamUUID());
                        if (msg.getRoutingDestination() != null)
                        {
                            writer.newLine();
                            writer.taggedValue("routingDestination", msg.getRoutingDestination());
                        }

                        writer.outdent();
                        writer.newLine();
                        writer.endTag("xmitData");
                    }
                } catch (SevereMessageStoreException se)
                {
                    // No FFDC code needed
                } catch (RuntimeException re)
                {
                    // No FFDC code needed
                }

                String text = null;
                //if we can easily get the text of the message then use that
                if (msg instanceof JsJmsTextMessage)
                {
                    try
                    {
                        text = ((JsJmsTextMessage) msg).getText();
                        if (text != null && text.length() > 40)
                            text = text.substring(0, 37) + "...";
                    } catch (UnsupportedEncodingException e)
                    {
                        // No FFDC code needed
                        text = "Unsupported message encoding";
                    }
                }
                else
                    text = String.valueOf(msg);

                writer.newLine();
                writer.taggedValue("data", text);
            }
        } catch (RuntimeException e)
        {
            // No FFDC code needed

            // As we're not locking the state down there's very slim chance of hitting
            // something like a NPE while we do this, we'll just catch it and ignore it
        }
    }